多线程的操作
线程的操作主要分为三种:创建线程、终止线程、回收线程;
创建线程
线程的创建函数如下:
样例1:创建两个线程,实现每隔 1s 打印一次信息
#include <stdio.h>
#include <pthread.h>
void *myThread1(void)
{
for(int i = 0 ; i < 100; i++) {
printf("%s: %d: This is the 1st pthread\n", __FILE__, __LINE__);
sleep(1);
}
return NULL;
}
void *myThread(void)
{
for(int i = 0; i < 100; i++) {
printf("%s: %d: This is the 2st pthread\n", __FILE__, __LINE__);
sleep(1);
}
return NULL;
}
int main()
{
int i = 0, ret = 0;
pthread_t pid1, pid2;
/*创建线程1*/
ret = pthread_create(&pid1, NULL, (void*)myThread1, NULL);
if(ret) {
printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
return 1;
}
/*创建线程2*/
ret = pthread_create(&pid2, NULL, (void*)myThread2, NULL);
if(ret) {
printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
例子2:创建一个线程实现参数传递
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *myThread(void *arg)
{
int *num;
num = (int *)arg;
printf("%s: %d: create parameter is %d\n", __FILE__, __LINE__, *num);
return (void *)0;
}
int main()
{
pthread_t pid;
int error;
int test = 4;
int *attr = &test;
/*创建线程1*/
error = pthread_create(&pid, NULL, (void*)myThread, (void *)attr);
if(error) {
printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
return 1;
}
pthread_join(pid, NULL);
return 0;
}
终止线程
终止线程有三种方式:
- 线程从执行函数返回,返回值就是线程的退出码;
- 线程被同一进程内的其他线程取消;
- 线程调用
pthread_exit()
函数退出;
- 如果线程是 分离线程,调用上述函数,线程资源会被系统回收,线程终止;
- 如果线程是 结合线程,调用上述函数,会释放线程资源,但是不会释放线程号,线程号直到主线程
pthread_join
返回后才释放;
注意:
- 如果主线程从
main()
调用返回时或调用exit()
时,整个进程内的所有线程都会终止。 - 如果是主线程调用了
pthread_exit
,则仅仅只是主线程本身终止,同一进程内的其他线程不受影响;
回收线程
回收线程函数如下:
注意:
- 回收线程函数只针对结合线程,它会阻塞当前线程,用以回收其他线程的线程号。
- 如果多个线程等待同一线程终止,则所有等待线程将一直等待目标线程终止;然后,一个等待线程成功返回,其余的等待线程将失败并返回 ESRCH 错误。
- 子线程要么设置为 分离状态,要么在主线程中使用
pthread_jion
回收子线程资源; - 主线程退出(main 函数运行到结尾),这个程序结束,所以主线程最好要使用
pthread_join
等待子线程运行结束; - 使用
pthread_join
的线程将会阻塞,直到子线程结束,pthread_join
函数返回; - 如果子线程使用
exit()
,则可以结束整个进程;