我编写了一个简单的演示程序,以便可以了解pthread_join()
功能。
[我知道如何使用pthread_condition_wait()
函数来允许异步线程,但是我试图了解如何使用pthread_join()
函数来完成类似的工作。
在下面的程序中,我将Thread 1s ID传递给Thread 2s函数。在Thread 2s函数内部,我调用pthread_join()
函数并传入Thread 1s ID。我期望这会导致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);
}
输出:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9FTER2MS5wbmcifQ==” alt =“在此处输入图像描述”>“ >>
我编写了一个简单的演示程序,以便可以理解pthread_join()函数。我知道如何使用pthread_condition_wait()函数来允许异步线程,但我...
当使用pthread_create()
创建线程时,两个线程同时开始执行,并且它们的执行顺序没有固定的顺序。该顺序取决于OS调度和可用处理器的数量等。在任何情况下,都无法确定,这也是线程的重点。
您调用未定义的行为。手册页:pthread_join()
从pthread_cond_wait()
(强调我的位置:)>
如果多个线程同时尝试与同一个线程联接,则结果是不确定的。