pthread编程,线程不会同时运行

时间:2015-03-28 10:35:40

标签: c multithreading pthreads

我的程序中包含以下代码:

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


    if (0 != pthread_create(&thrs[i], NULL, thr_main,
                &args[i]))
    {
        /* handle error */
    }

    printf("thread %d created.\n", i);

    if (0 != pthread_join(thrs[i], &thread_status))
    {
        /* handle error */
    }

    printf("joined thread %d\n", i);
}

但是我注意到线程没有同时运行,第二个线程只在第一个线程完成执行后才开始执行。我是pthread编程的新手。有人能告诉我什么是同时启动某些线程的正确方法吗?

1 个答案:

答案 0 :(得分:2)

这是因为您在创建它之后立即pthread_join每个线程,即您在启动线程n之前等待线程n+1完成。

相反,请尝试:

for (i = 0; i < numthrs; i++)
{
    if (0 != pthread_create(&thrs[i], NULL, thr_main,
                &args[i]))
    {
        /* handle error */
    }

    printf("thread %d created.\n", i);
}

for (i = 0; i < numthrs; i++)
{
    if (0 != pthread_join(thrs[i], &thread_status))
    {
        /* handle error */
    }

    printf("joined thread %d\n", i);
}
相关问题