4- pthread其他接口

參考:https://blog.csdn.net/u010383937/article/details/78215287

https://www.cnblogs.com/lijunamneg/archive/2013/01/25/2877211.html

 

phtread_join():監控等待線程結束,阻塞接口。類似進程的wait()

pthread_cancel():需要設置被取消線程取消使能、取消類型(延遲、異步)。然後在自己線程裏取消該線程

 

1- phtread_join():監控等待線程結束,阻塞接口。類似進程的wait()

pthread_exit():線程自行退出,類似進程的exit()

示例:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>

void * thread_strat(void *message)
{
    printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
	
	sleep(1);
	printf("%s[%d] thread=%lu  here is thread\n",__func__,__LINE__,pthread_self());
	
	/*線程自行退出:return、pthread_exit*/
	pthread_exit(NULL);
	//return message;
}

int main(void)
{
	pthread_t thread;
	int ret;
	const char *message = "creat thread succ";
	
	/*只是創建線程,並不執行*/
	ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
	if(!ret)
	{
		perror("pthread_creat");
	}
	printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
	
	/*等待線程thread結束,期間自己阻塞掛起。當thread結束後才返回*/
	pthread_join(thread,NULL);
	printf("%s[%d] i'm comming!\n",__func__,__LINE__);

	return 0;
}

 

2-  線程取消和清理

pthread_cancel():需要設置被取消線程取消使能、取消類型(延遲、異步)。然後在自己線程裏取消該線程

pthread_cleanup_push/pop():釋放線性資源

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>

void * thread_strat(void *message)
{
    printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
	
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);//PTHREAD_CANCEL_DEFERRED
	
	while(1)
	{
		printf("%s[%d] thread=%lu  here is thread\n",__func__,__LINE__,pthread_self());
	}
	
	
	/*線程自行退出:return、pthread_exit*/
	pthread_exit(NULL);
	//return message;
}

int main(void)
{
	pthread_t thread;
	int ret;
	const char *message = "creat thread succ";
	
	/*只是創建線程,並不執行*/
	ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
	if(!ret)
	{
		perror("pthread_creat");
	}
	
	printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
	
	/*取消線程*/
	pthread_cancel(thread);	
	printf("%s[%d] i'm comming!\n",__func__,__LINE__);

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章