c 创建线程

来源:undefined 2025-03-02 04:34:31 1012

在Python中,可以使用`threading`模块来创建线程。下面是一个简单的例子,展示如何使用多线程来写入1000个单词到文件中:

```python

import threading

# 定义一个全局的变量来保存要写入的单词

words = []

# 定义一个线程函数,写入指定数量的单词到文件中

def write_to_file(num_words):

global words

for i in range(num_words):

words.append("Word " + str(i+1) + " ")

with open("output.txt"

"a") as f:

f.writelines(words)

# 创建两个线程分别写入500个单词

thread1 = threading.Thread(target=write_to_file

args=(500

))

thread2 = threading.Thread(target=write_to_file

args=(500

))

# 启动线程

thread1.start()

thread2.start()

# 等待线程执行完毕

thread1.join()

thread2.join()

print("Writing 1000 words to file completed.")

```

上述代码中,我们首先定义了一个全局的`words`列表来保存要写入的单词。然后定义了一个线程函数`write_to_file(num_words)`,该函数接受一个参数`num_words`,表示要写入的单词数量。在函数中,我们通过循环向`words`列表中添加指定数量的单词,然后将`words`列表中的内容写入到文件`output.txt`中。

接着,我们创建了两个线程`thread1`和`thread2`,分别用于写入500个单词。然后分别启动这两个线程,等待它们执行完毕。

*,我们打印出消息表示写入1000个单词到文件已经完成。这样,我们就使用多线程的方式写入了1000个单词到文件中。

上一篇:盒子排列模块 下一篇:js对象转字符串

最新文章