abo*_*ria 0 multithreading pthreads process
我正在学习有关线程和Linux上C语言中的线程编程的知识。我了解的是,加入线程只是调用线程并等待其执行,就像等待子进程运行一样。但是不知道为什么在尝试加入一个线程时最终会调用两个线程!
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void *start1()
{
printf("Hello from Thread 1\n");
}
void *start2()
{
printf("Hello from Thread 2\n");
}
void main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,start1,NULL);
pthread_create(&t2,NULL,start2,NULL);
pthread_join(t1,NULL);
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,输出如下:
[root@localhost]# ./a.out
Hello from Thread 1
Hello from Thread 2
Run Code Online (Sandbox Code Playgroud)
我希望它仅调用start1的代码。
pthread_join等待线程退出并pthread_create创建并启动线程,无论是否加入该线程。
在您的示例中,程序中有3个线程(包括主线程)。但是,如果正在执行该main功能的主线程在2个其他线程之前退出,则整个程序将终止,并且其他线程可能没有机会输出任何东西。
最重要的是,您应该记住,程序线程的执行顺序是不确定的,这包括但不一定保证同时执行。因此,在您的示例中,当您仅等待主线程中的另一个线程时,无法确定在等待第一个线程时第二个附加线程是否有机会运行(并退出)。
如果出于某种原因,您只希望运行一个线程,则应该仅启动一个线程(显然是:)),或者采用某种同步机制(例如互斥量或条件变量),这将使第二个线程等待某种条件发生。在工作之前发生。