多线程的简单使用

简单探究多线程的使用

Posted by Jerry Chen on September 13, 2019

开始

头文件包含:#include <pthread.h>

编译连接参数:-lpthread

创建线程

函数原型:

1
2
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,
(void*)(*start_rtn)(void*),void *arg);

常用如下:

1
2
3
4
5
6
7
void *func(void *arg){
    printf("new thread<tid:%lu> running!\n",pthread_self());
    return NULL;
}
...
pthread_t tid;
pthread_create(&tid, NULL, func, NULL);

pthread_create执行后相当于新建了低配版进程在后台执行func函数。主线程还会继续执行下去。

等待线程自然结束

函数原型:

1
int pthread_join(pthread_t thread, void **retval);

主要用途是阻塞等待thread指定的线程结束,存储返回值到retval。

通俗的讲,等待线程正常退出合并到主线程。

比如放在主线程(一般指主函数)中执行,防止主函数return后进程被终止,而要等待指定线程结束后再执行后面的指定。

常用如下:pthread_join(tid,NULL);

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <pthread.h>
void *run(void *arg) {
	int ret=(int)arg;
	int count=5;
	while(count--){
		printf("new thread<tid:%lu> running,arg = %d\n",pthread_self(),ret);
		sleep(1);
	}
	return (void*) ret;
}
int main( void )
{
	pthread_t tid;
	pthread_t tid1;
	pthread_t tid2;
	int s,s1,s2 = 0;
	//开始有一个主线程,然后创建3个线程后台执行run
	pthread_create(&tid, NULL, run, (void*)0);
	pthread_create(&tid1, NULL, run, (void*)1);
	pthread_create(&tid2, NULL, run, (void*)2);
	//依次等待三个进程结束
	pthread_join(tid,(void**)&s);
	pthread_join(tid1,(void**)&s1);
	pthread_join(tid2,(void**)&s2);

	printf("I am main thread;tid = %lu\n",pthread_self());
	printf("exit code :%d,%d,%d\n",s,s1,s2);                                 
	return 0;
}

完成后编译:

1
gcc -o pthread_demo pehread_demo.c -lpthread

结果如下:

分离线程

函数原型:

1
int pthread_detach(pthread_t thread);

如线程处于被分离状态下,主线程退出,被分离线程也会退出,被分离线程只是不需要使用pthread_join函数来释放内存资源。