day27
- 创建一个子线程,子线程申请内存,通过清理函数进行free,子线程停留在read标准输入,主线程cancel子线程,子线程能够通过清理函数free对应的malloc的内存
#include <func.h>
//清理函数
void cleanup(void *p)
{
free(p);
p=NULL;
printf("I am cleanup\n");
}
void * threadFunc(void *p)
{
char *pStr=(char*)malloc(20);
pthread_cleanup_push(cleanup,pStr);
strcpy(pStr,"hello");
printf("I am child thread,%s\n",pStr);
sleep(3);//被cancel,没有free,内存泄漏
printf("I am child thread I am wake\n");
pthread_exit(NULL);
pthread_cleanup_pop(0);
}
int main()
{
pthread_t pthid;
int ret;
ret=pthread_create(&pthid,NULL,threadFunc,NULL);
THREAD_ERROR_CHECK(ret,"pthread_create");
ret=pthread_cancel(pthid);
THREAD_ERROR_CHECK(ret,"pthread_cancel");
long threadRet;
ret=pthread_join(pthid,(void**)&threadRet);
THREAD_ERROR_CHECK(ret,"pthread_join");
//线程被cancel以后,接收到的返回值是-1
printf("child exit code=%ld\n",threadRet);
return 0;
}
- 创建一个子线程,cancel子线程,在子线程中push两个清理函数,感受清理函数的执行顺序
- 子线程,主线程,同时对一个主线程局部变量各加2千万,通过加锁,实现最终效果是4千万并统计时间。
4、编写火车站卖票,两个子线程卖票,什么时候会有负票,什么时候不会,都写一下感受一下
#include <func.h>
typedef struct{
pthread_mutex_t mutex;
long tickets;//票数
}thData;
void* threadfunc1(void *p)
{
thData *p1=(thData*)p;
while(1)
{
pthread_mutex_lock(&p1->mutex);//先锁后判断,防止最后一张票两人同时抢,若是先判断两人都了锁
if(p1->tickets>0)
{
printf("I am windows1,I will sale tickets %ld\n",p1->tickets);
p1->tickets--;
printf("I am windows1,sale ok %ld\n",p1->tickets);
pthread_mutex_unlock(&p1->mutex);
}else{
pthread_mutex_unlock(&p1->mutex);
break;
}
//sleep(1);
}
}
void* threadfunc2(void *p)
{
thData *p1=(thData*)p;
while(1)
{
pthread_mutex_lock(&p1->mutex);
if(p1->tickets>0)
{
printf("I am windows2,I will sale tickets %ld\n",p1->tickets);
p1->tickets--;
printf("I am windows2,sale ok %ld\n",p1->tickets);
pthread_mutex_unlock(&p1->mutex);
}else{
pthread_mutex_unlock(&p1->mutex);
break;
}
//sleep(1);
}
}
int main()
{
thData threadinfo;//结构体
int ret;
ret=pthread_mutex_init(&threadinfo.mutex,NULL);
if(ret!=0)
{
printf("pthread_mutex_init failed ret=%d\n",ret);
return -1;
}
pthread_t pthid1,pthid2;
threadinfo.tickets=20;
pthread_create(&pthid1,NULL,threadfunc1,&threadinfo);
pthread_create(&pthid2,NULL,threadfunc2,&threadinfo);
pthread_join(pthid1,NULL);
pthread_join(pthid2,NULL);
return 0;
}
会有负票的情况:
5.启动子线程,处于wait状态,主线程signal子线程,确保子线程正常唤醒
——————————————————————————————
高难度作业:
1、通过使用共享内存,外加设置线程锁属性pthread_mutexattr_getpshared,用mutex实现两个进程各加2千万,最终实现4千万。