gpt4 book ai didi

c - 如何生成 n 个线程?

转载 作者:太空狗 更新时间:2023-10-29 17:03:24 24 4
gpt4 key购买 nike

我正在尝试编写一个多线程程序,线程数基于命令行输入,因此我无法对预先声明的线程进行硬编码。这是一种有效的方法吗?

int threads = 5; // (dynamic, not hard-coded)
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);

for (i = 0; i < threads; i++) {
pthread_t foobar;
thread[i] = foobar; // will this cause a conflict?
}

for (i = 0; i < threads; i++) {

int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL);

if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}

这是我根据下面建议的修改得出的结果。似乎工作正常。

int threads = 5;
int i;

pthread_t * thread = malloc(sizeof(pthread_t)*threads);

for (i = 0; i < threads; i++) {

int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);

if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
// pthread_join(thread[i], NULL); // don't actually want this here :)
}

sleep(1); // main() will probably finish before your threads do,
free(thread); // so we'll sleep for illustrative purposes

最佳答案

第一个循环是什么?它是否将数组元素设置为未初始化值?

所以我认为这就是你需要的:

int threads = 5, i = 0, ret = -1;

pthread_t * thread = malloc(sizeof(pthread_t)*threads);

for (i = 0; i < threads; i++) {

ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);

if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}

它生成threads 个线程,在每个线程中启动foobar_function。你在thread数组中有(如果一切顺利的话:))它们的id。因此,例如,您可以通过调用 pthread_cancel(thread[1]) 等来取消第二个线程。

关于c - 如何生成 n 个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4964142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com