3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python3.0でthreading

Posted at

経緯

この辺を参考に解説されていることをやってみようかと思い。

実践

thread.py
import threading

class MyMessenger(threading.Thread): #inherits the thread built-in function
	def run(self): #whenever you call this func. you need "def run"
		for _ in range(10): #when you dont really wanna use the counter var. python convention. just to loop
			print(threading.currentThread().getName())

x = MyMessenger(name='Send out messages')
y = MyMessenger(name='Receive messages')
x.start() #whenever you create thread, you wanna call start function
y.start() #goes to the class and looks for a func. called "run"

最初の何回かはAttributeError: 'module' object has no attribute 'Thread'と怒られたがそれはファイルの名前をthreading.pyにしていたからだと発見

動かしてみると

Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Send out messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages
Receive messages

もう一度!

Send out messages
Send out messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Receive messages

Threadとは

簡単に言うとThreadを使えば、

x = MyMessenger(name='Send out messages')
y = MyMessenger(name='Receive messages')

でオブジェクトを作った後、

x.start() 
y.start() 

の2つの操作を(順番はあるものの)前者の完了を待たずに同時に行える。
上から下という順番があるからこのスクリプトを起動すると90%の確率でSend out messagesが最初に出る、んだと思う、多分。

つまり

for _ in range(10):
    print(threading.currentThread().getName())

xyがほぼ同時にループをしていることになる。そのため毎回起動する度に順番が異なる。x.start()によってSend out messagesという名前のthreadを作りfor loopに入っていく。ただthreadは基本的には推奨されていないmethod。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?