【问题标题】:How to spawn n threads?如何产生n个线程?
【发布时间】:2011-02-10 23:56:09
【问题描述】:

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

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 = argv[3] 位中的字符串。您必须使用atoi 或 sscanf
  • 好吧,pthread_join() 是它所在的位置,您应该创建线程,然后等待它完成,然后再生成下一个线程。所以实际上你在这里是准单线程的:)
  • 当我在没有连接的情况下运行它时,它认为它不会执行函数......(我让 foobar_function 只是打印出一行快速的文本)。我错过了一步吗? .. EDIT 实际上,我猜它正在工作.. 有时它会打印出文本,但大多数时候它不会:P.

标签: c pthreads


【解决方案1】:

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

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

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]) 等来取消第二个线程。

【讨论】:

  • @Brian D:你指定为pthread_create()的第三个参数的线程函数。
  • 是的,我相信这就是我想要做的。在我下面的例子中,因为它是一个静态数量的 pthread,他们只写 pthread_t t1;pthread_t t2; 然后用两个不同的函数初始化它们,所以我试图弄清楚如何动态地创建 n 个线程.
  • @Brian D:所以跳过那部分(因为 pthread_t 的性质是未知的,不能将其设置为任何类型的未定义)。您在第二个周期中获得线程的 ID(并启动线程)。
  • 我没完全理解..你能举个例子吗?
  • 注意:检查malloc的结果总是一个好主意,因为操作系统有时无法为您提供请求的内存块。
【解决方案2】:

第一个for 循环不是有效的C,我不确定你想要它做什么。只需删除它,其余代码看起来就可以了,除了foobar_function 上的错误转换。演员应该是:

(void *(*)(void *))foobar_function

但除非类型已经是 this 或非常接近的类型,否则您的程序可能具有未定义的行为。最好修复函数签名,这样就不需要强制转换了。

【讨论】:

    【解决方案3】:

    如果您尝试编写多线程程序,但不了解如何分配动态大小的数据结构,您可能做错了错误

    在跑步之前先学会走路。

    考虑使用更简单的语言,并避免使用(显式)线程。

    线程很难正确使用;动态大小的数组很容易实现(在 C 中甚至相当容易)

    【讨论】:

    • 作为家庭作业时,语言或显式线程的使用几乎没有选择:)
    猜你喜欢
    • 2014-01-01
    • 2021-12-18
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多