一、线程终止:
1.pthread_exit函数:
只需终止某个线程而不需要终止整个进程的三个方法:
void pthread_exit(void *retval);
2.pthread_cancel函数
int pthread_cancel(pthread_t thread)
二、线程等待
2.pthread_join函数
int pthread_join(pthread_t thread, void **retval);
功能:等待线程的结束
参数:pthread_t thread:线程ID
void **retval:它指向一个指针指向线程的返回值,输出型参数,一般填NULL
注意⚠️:调用该函数的线程将被挂起等待,直到id为指定的线程结束终止,thread线程以不同的方法终止,通过pthread_join得到的终
止状态是不同的,总结如下:
a.如果thread线程是通过return返回,retval所指向的单元里存放的是thread线程函数的返回值
b.如果thread线程被别的线程调用pthread_cancel函数异常终止掉,retval所指向的单元里存放到是常数PTHREAD_
CANCELED
c.如果thread线程是调用pthread_exit函数终止的,retval所指向的单元里存放是传给pthread_exit函数的参数,(即这里的retval参数是和pthread_exit函数的参数是相关联的)
d.如果对thread线程终止状态不感兴趣直接传NULL即可。
#include
#include
#include
#include
#include
void *thread1( void *arg )
{
printf("thread 1 returning ... \n");
int *p = (int*)malloc(sizeof(int));
*p = 1;
return (void*)p;
} v
oid *thread2( void *arg )
{
printf("thread 2 exiting ...\n");
int *p = (int*)malloc(sizeof(int));
*p = 2;
pthread_exit((void*)p);
} v
oid *thread3( void *arg )
{
while ( 1 ){ //
printf("thread 3 is running ...\n");
sleep(1);
} r
eturn NULL;
} i
nt main( void )
{
pthread_t tid;
void *ret;
// thread 1 return
pthread_create(&tid, NULL, thread1, NULL);
pthread_join(tid, &ret);
printf("thread return, thread id %X, return code:%d\n", tid, *(int*)ret);
free(ret);
// thread 2 exit
pthread_create(&tid, NULL, thread2, NULL);
pthread_join(tid, &ret);
printf("thread return, thread id %X, return code:%d\n", tid, *(int*)ret);
free(ret);
// thread 3 cancel by other
pthread_create(&tid, NULL, thread3, NULL);
sleep(3);
pthread_cancel(tid);
pthread_join(tid, &ret);
if ( ret == PTHREAD_CANCELED )
printf("thread return, thread id %X, return code:PTHREAD_CANCELED\n", tid);
else
printf("thread return, thread id %X, return code:NULL\n", tid);
}
三、线程分离:
int pthread_detach(pthread_t thread)
#include
#include
#include
#include
#include
void *thread_run( void * arg )
{
pthread_detach(pthread_self());
printf("%s\n", (char*)arg);
return NULL;
} i
nt main( void )
{
pthread_t tid;
if ( pthread_create(&tid, NULL, thread_run, (void*)"thread1 run...") != 0 ) {
printf("create thread error\n");
return 1;
} i
nt ret = 0;
sleep(1);//很重要,要让线程先分离,再等待
if ( pthread_join(tid, NULL ) == 0 ) {
printf("pthread wait success\n");
ret = 0;
} else {
printf("pthread wait failed\n");
ret = 1;
} r
eturn ret;
}
四、线程互斥
1.线程互斥相关概念
2.互斥量:mutex
#include
#include
#include
#include
#include
int ticket = 100;
void *route(void *arg)
{
char *id = (char*)arg;
while ( 1 ) {
if ( ticket > 0 ) {
usleep(1000);
printf("%s sells ticket:%d\n", id, ticket);
ticket--;
} else {
break;
}
}
} i
nt main( void )
{
pthread_t t1, t2, t3, t4;
pthread_create(&t1, NULL, route, "thread 1");
pthread_create(&t2, NULL, route, "thread 2");
pthread_create(&t3, NULL, route, "thread 3");
pthread_create(&t4, NULL, route, "thread 4");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
}
根据上面的代码,发现没有正确的获取到我们想要的结果,为什么呢?
解决办法请看Linux线程(三)