CFSection9's Studio.

Thread

字数统计: 185阅读时长: 1 min
2019/03/21 Share

Thread in C code user space

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
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void *thread_func(void *ptr)
{
int i;
for(i=0;i<5;i++)
{
printf("New pthread running ,count: %d\n",i);
}

}

int main(void)
{
pthread_t pId;
int i,ret;
//创建子线程,线程id为pId
ret = pthread_create(&pId,NULL,thread_func,NULL);

if(ret != 0)
{
printf("create pthread error!\n");
exit(1);
}

for(i=0;i < 3;i++)
{
printf("Process running ,count : %d\n",i);
}

printf("Process will exit when new pthread is over\n");
//等待线程pId的完成
pthread_join(pId,NULL);
printf("Process exit\n");

return 0;

}

编译的时候要加上-lpthread, 运行结果如下:

1
2
3
4
5
6
7
8
9
10
Process running ,count : 0
New pthread running ,count: 0
Process running ,count : 1
New pthread running ,count: 1
Process running ,count : 2
New pthread running ,count: 2
Process will exit when new pthread is over
New pthread running ,count: 3
New pthread running ,count: 4
Process exit

CATALOG
  1. 1. Thread in C code user space