thread

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 <stdlib.h>
#include <pthread.h>
#include <unistd.h>

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

}

int main(void)
{
pthread_t pId;
int i,ret;

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 : %dn",i);
}

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

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