一、线程的概念
1、进程的多个线程共享:
1)同一地址空间,因此Text Segment、Data Segment都是共享的,如果定义一个函数,在各线程中都可以调用,如果定义一个全局变量,在各线程中都可以访问到,除此之外,各线程还共享以下进程资源和环境
1、优点
1)性能损失
1、创建线程要用pthread_creat函数
参数:
错误信息:
代码实现线程的创建:
1 #include
2 #include
3 #include
4 #include
5 #include
6
7 void *thread_run(void *arg){
8 printf("I am new thread :pid:%d,thread:%u\n",getpid(),pthread_self());
9 sleep(5);
10 return (void*)3;
11 }
12
13 int main(){
14 pthread_t tid;
15 int ret;
16 if((ret=pthread_create(&tid,NULL,thread_run,NULL))!=0){
17 fprintf(stderr,"pthread_create:%s\n",strerror(ret));
18 exit(EXIT_FAILURE);
19 }
20 printf("i am main thread:pid:%d,thread:%u\n",getpid(),pthread_self());
21 pthread_join(tid,NULL);
22 return 0;
23 }
在这里注意,pthread.h不是Linux默认的库,因此在链接时需要使用静态库libthread.a,所以在编译时要加-lpthread参数,如下:
可以看到两个线程属于同一个进程。
五、线程等待
pthread_join函数---等待线程结束
1 #include
2 #include
3 #include
4 #include
5 #include
6
7 void *thread1(void *arg){
8 printf("thread 1 returning...\n");
9 int *p=(int*)malloc(sizeof(int));
10 *p=1;
11 return (void*)p;
12 }
13
14 void *thread2(void *arg){
15 printf("thread 2 exiting...\n");
16 int *p=(int*)malloc(sizeof(int));
17 *p=2;
18 pthread_exit((void*)p);
19 }
20
21 void *thread3(void *arg){
22 while(1){
23 printf("thread3 is running..\n");
24 sleep(1);
25 }
26 return NULL;
27 }
28
29 int main(){
30 pthread_t tid;
31 void *ret;
32
33 //thread1 return
34 pthread_create(&tid,NULL,thread1,NULL);
35 pthread_join(tid,&ret);
36 printf("thread return,thread id %X,return code:%\n",tid,*(int*)ret);
37 free(ret);
38
39 //thread2 exit
40 pthread_create(&tid,NULL,thread2,NULL);
41 pthread_join(tid,&ret);
42 printf("thread rerurn,thread id %X,return code:%d\n",tid,*(int*)ret);
43 free(ret);
44
45 //thread 3 cancel by other
46 pthread_create(&tid,NULL,thread3,NULL);
47 sleep(3);
48 pthread_cancel(tid);
49 pthread_join(tid,&ret);
50 if(ret==PTHREAD_CANCELED)
51 printf("thread return,thread id %X,return code:PTHREAD_CANCELED\n",tid);
52 else
53 printf("thread return,thread id %X,return code:NULL\n",tid);
54 }
1 #include
2 #include
3 #include
4 #include
5 #include
6
7 void *thread_run(void *arg){
8 pthread_detach(pthread_self());
9 printf("%s\n",(char*)arg);
10 return NULL;
11 }
12
13 int main(){
14 pthread_t tid;
15 if(pthread_create(&tid,NULL,thread_run,"thread1 run...")!=0){
16 printf("create thread error\n");
17 return 1;
18 }
19 int ret=0;
20 sleep(1);
21 if(pthread_join(tid,NULL)==0){
22 printf("pthread wait success\n");
23 ret=0;
24 }
25 else{
26 printf("pthread wait failed\n");
27 ret=1;
28 }
29 return ret;
30 }