#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
typedef struct node
{
int num;
struct node *next;
}node,*pnode;
static pnode head = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void cleanFunc(void *args)
{
printf("I am cleanFunc\n");
pthread_mutex_unlock(&mutex);
//pthread_exit((void*)2); //这里是线程exit退出或者异常退出执行的函数,所以都是由main线程来执行,不能退出main线程,不然在这个函数死循环
}
void *pthFunc(void *args)
{
pnode p = NULL;
while(1)
{
pthread_cleanup_push(cleanFunc,NULL);
pthread_mutex_lock(&mutex);
if(NULL==head)
{
pthread_cond_wait(&cond,&mutex);
}
printf("consume %d \n",head->num);
p = head;
head = head->next;
free(p);
if(NULL==head)
{
pthread_mutex_unlock(&mutex);
pthread_exit((void*)1);
}
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_cleanup_pop(0);
}
}
int main(void)
{
pthread_t pthId;
pthread_create(&pthId,NULL,pthFunc,NULL);
pnode p = NULL;
for(int i=0;i<5;i++)
{
p = (pnode)calloc(1,sizeof(node));
pthread_mutex_lock(&mutex);
p->num = i+1;
p->next = head;
head = p;
printf("product %d\n",p->num);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
//pthread_exit(NULL); //退出main线程,子线程就可以自己执行完毕,直到退出,但是不要这么做
sleep(3); //让子线程消费一会,然后main再执行下面的取消操作;
int ret;
ret = pthread_cancel(pthId);
printf("cancel ret = %d\n",ret);
int i;
ret = pthread_join(pthId,(void**)&i);
printf("join ret = %d , val = %d\n",ret,(int)i);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
//子线程被cancel,所以返回值-1
//sleep 3s,子线程就自己指向完毕了
|
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
typedef struct node
{
int num;
struct node *next;
}node,*pnode;
static pnode head = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void cleanFunc(void *args)
{
printf("I am cleanFunc\n");
pthread_mutex_unlock(&mutex);
}
void *pthFunc(void *args)
{
pnode p = NULL;
while(1)
{
pthread_cleanup_push(cleanFunc,NULL);
pthread_mutex_lock(&mutex);
if(NULL==head)
{
pthread_cond_wait(&cond,&mutex);
}
printf("consume %d \n",head->num);
p = head;
head = head->next;
free(p);
if(NULL==head)
{
pthread_mutex_unlock(&mutex);
pthread_exit((void*)1);
}
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_cleanup_pop(0);
}
}
int main(void)
{
pthread_t pthId;
pthread_create(&pthId,NULL,pthFunc,NULL);
pnode p = NULL;
for(int i=0;i<5;i++)
{
p = (pnode)calloc(1,sizeof(node));
pthread_mutex_lock(&mutex);
p->num = i+1;
p->next = head;
head = p;
printf("product %d\n",p->num);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_join(pthId,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
|