参考网址:

pthread 线程基本函数_chenwh_cn的博客-CSDN博客_pthread函数

Pthread线程基础学习_我的梦-CSDN博客_pthread教程

创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *thread_fun(void* arg)
{
int num = *((int*)arg);
printf("int the new thread: num = %d\n", num);
}

int main(int argc, char *argv[])
{
pthread_t tid;
int test = 100;

pthread_create(&tid, NULL, thread_fun, (void *)&test);
while(1);
return 0;
}

线程等待

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *thead_fun(void *arg)
{
static int ret = 5; // thread_join.cpp:7:13: warning: address of local variable ‘ret’ returned [-Wreturn-local-addr]
sleep(1);
pthread_exit((void*)&ret);
//return (void*)&ret;
}
// 等待线程结束并回收线程资源,此函数会阻塞,类似进程的 wait() 函数。如果线程已经结束,那么该函数会立即返回
int main(int argc, char *argv[])
{
pthread_t tid;
void *ret = NULL;

pthread_create(&tid, NULL, thead_fun, NULL);
pthread_join(tid, &ret);
printf("ret = %d\n", *((int*)ret));

return 0;
}

分离线程

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

void *thead_fun(void *arg)
{
for(int i=0; i<3; i++)
{
printf("thread is runing\n");
sleep(1);
}
return NULL;
}

int main(int argc, char *argv[])
{
pthread_t tid;

pthread_create(&tid, NULL, thead_fun, NULL);
pthread_detach(tid);
if (pthread_join(tid, NULL)) // 立即返回,调用失败
{
printf("join not working\n");
}
printf("after join\n");
sleep(5);
printf("master is leaving\n");
return 0;
}

退出线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *thead_fun(void *arg)
{
static int ret = 5; // thread_join.cpp:7:13: warning: address of local variable ‘ret’ returned [-Wreturn-local-addr]
sleep(1);
pthread_exit((void*)&ret);
//return (void*)&ret;
}

int main(int argc, char *argv[])
{
pthread_t tid;
void *ret = NULL;

pthread_create(&tid, NULL, thead_fun, NULL);
pthread_join(tid, &ret);
printf("ret = %d\n", *((int*)ret));

return 0;
}

取消线程

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<stdlib.h>
#include <pthread.h>
void *thread_fun(void *arg)
{
int i=1;
printf("thread start \n");
while(1)
{
i++;
// 调用pthread_testcancel,让内核去检测是否需要取消当前线程。
pthread_testcancel();
}
return (void *)0;
}
int main()
{
void *ret=NULL;
int iret=0;
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
sleep(1);

pthread_cancel(tid);//取消线程
pthread_join(tid, &ret);
printf("thread 3 exit code %d\n", (int)ret);

return 0;

}