我写了一个简单的演示程序,以便我可以理解pthread_join()
功能。
我知道如何使用pthread_condition_wait()
函数允许异步线程,但我试图了解如何使用pthread_join()
功能。
在下面的程序中我通过线程1s ID to 线程 2s功能。里面线程 2s我称之为函数pthread_join()
函数并传入线程1sID。我预计这会导致Thread 1先运行,然后运行Thread 2运行第二,但我得到的是它们都同时运行。
这是因为只有一个线程可以使用pthread_join()
一次运行并且我已经在使用pthread_join()
当我从调用它时函数主线程?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionCount1();
void *functionCount2(void*);
int main()
{
/*
How to Compile
gcc -c foo
gcc -pthread -o foo foo.o
*/
printf("\n\n");
int rc;
pthread_t thread1, thread2;
/* Create two thread --I took out error checking for clarity*/
pthread_create( &thread1, NULL, &functionCount1, NULL)
pthread_create( &thread2, NULL, &functionCount2, &thread1)
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("\n\n");
exit(0);
}
void *functionCount1()
{
printf("\nFunction 1");
sleep(5);
printf("\nFunction 1");
return(NULL);
}
void *functionCount2(void* argument)
{
pthread_t* threadID = (pthread_t*) argument;
pthread_join(*threadID, NULL);
printf("\nFunction 2");
sleep(5);
printf("\nFunction 2");
return(NULL);
}
Output:
当使用创建线程时pthread_create()
,两个线程同时开始执行,并且它们的执行顺序没有固定的顺序。该顺序取决于操作系统调度和可用处理器的数量等。在任何情况下,这都无法确定,这就是线程的意义所在。
当你打电话时会发生什么pthread_join()
,调用者等待连接的线程终止。所以主线程等待thread1
终止然后为thread2
。但是当主要等待时thread1
, thread2
可能已经完成执行并终止。在这种情况下,pthread_join(thread2, NULL);
会立即返回。
你的代码中有一个更大的问题。你正在路过thread1
的 ID 至thread2
。但如果thread1
之前完成执行thread2
开始,那么您将使用无效的线程标识符,导致未定义的行为。另一个问题是你的主线程和thread2
都试图加入thread1
。简而言之,pthread_join()
不是多线程之间同步的正确工具。正如您所说,您正在使用条件变量/互斥体来实现此目的。
我建议你删除pthread_join()
from thread2
,要修复未定义的行为,如果您想要串行执行线程,那么您必须一个接一个地创建线程并让它们等待前一个线程终止(pthread_join()
)。但这样做的实际用途很少。或者让线程在执行任何操作之前等待条件变量,您可以使用条件变量使线程按照您想要的顺序进行通信。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)