Linux多线程编程快速入门

2019-10-10 16:07:50于海丽

程序实例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void printids(const char *s){
 pid_t pid;
 pthread_t tid;
 pid = getpid();
 tid = pthread_self();
 printf("%s, pid %lu tid %lu (0x%lx)n",s,(unsigned long)pid,(unsigned long)tid,
 (unsigned long)tid);
}

void *thread_func(void *arg){
 printids("new thread: ");
 return ((void*)0);
}
int main() {
 int err;
 pthread_t tid;
 err = pthread_create(&tid,NULL,thread_func,NULL);
 if (err != 0) {
  fprintf(stderr,"create thread fail.n");
 exit(-1); 
 }
 printids("main thread:");
 sleep(1); 
 return 0;
}

注意上述的程序中,主线程休眠一秒,如果不休眠,则主线程不休眠,则其可能会退出,这样新线程可能不会被运行,我自己注释掉sleep函数,发现好多次才能让新线程输出。

编译命令:

gcc -o thread thread.c -lpthread

运行结果如下:

main thread:, pid 889 tid 139846854309696 (0x7f30a212f740)
new thread: , pid 889 tid 139846845961984 (0x7f30a1939700)

可以看到两个线程的进程ID是相同的。其共享进程中的资源。

4. 线程终止

线程的终止分两种形式:被动终止和主动终止

被动终止有两种方式:

1.线程所在进程终止,任意线程执行exit、_Exit或者_exit函数,都会导致进程终止,从而导致依附于该进程的所有线程终止。
2.其他线程调用pthread_cancel请求取消该线程。

主动终止也有两种方式:

1.在线程的入口函数中执行return语句,main函数(主线程入口函数)执行return语句会导致进程终止,从而导致依附于该进程的所有线程终止。
2.线程调用pthread_exit函数,main函数(主线程入口函数)调用pthread_exit函数, 主线程终止,但如果该进程内还有其他线程存在,进程会继续存在,进程内其他线程继续运行。

线程终止函数:

include <pthread.h>
void pthread_exit(void *retval);

线程调用pthread_exit函数会导致该调用线程终止,并且返回由retval指定的内容。
注意:retval不能指向该线程的栈空间,否则可能成为野指针!

5. 管理线程的终止

5.1 线程的连接

一个线程的终止对于另外一个线程而言是一种异步的事件,有时我们想等待某个ID的线程终止了再去执行某些操作,pthread_join函数为我们提供了这种功能,该功能称为线程的连接:

include <pthread.h>
int pthread_join(pthread_t thread, void **retval);

参数说明:

thread(输入参数),指定我们希望等待的线程 
retval(输出参数),我们等待的线程终止时的返回值,就是在线程入口函数中return的值或者调用pthread_exit函数的参数