#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define THREAD_MAX 4
pthread_mutex_t mutex;
pthread_t thread[THREAD_MAX];
static int tries;
static int started;
void print_it(int *arg)
{
pthread_t tid;
tid = pthread_self();
printf("Thread %lx was canceled on its %d try.\n",tid,*arg);
}
void *Search_Num(int arg)
{
pthread_t tid;
int num;
int k=0,h=0,j;
int ntries;
tid = pthread_self();
/*while(pthread_mutex_trylock(&mutex) == EBUSY)
{
printf("**************busy****************\n");
pthread_testcancel();
}*/
srand(arg);
num = rand()&0xFFFFFF;
//pthread_mutex_unlock(&mutex);
printf("thread num %lx\n",tid);
ntries = 0;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
pthread_cleanup_push((void *)print_it,(void *)&ntries);
while(1)
{
num = (num+1)&0xffffff;
ntries++;
if(arg == num)
{
//只允许一个线程操作此处
while(pthread_mutex_trylock(&mutex) == EBUSY) {
//一个线程操作后其余线程进入次循环挂起,等待pthread_cancel函数发送cancel信号终止线程
k++;
if(k == 10000)
{
printf("----------2busy2-----------\n");
}
pthread_testcancel();
}
tries = ntries;
//pthread_mutex_unlock(&mutex); //如果加上这句话,将会有好几个线程找到主函数中设定的值pid
printf("Thread %lx found the number!\n",tid);
for(j = 0;j<THREAD_MAX;j++)
{
if(thread[j]!=tid)
{
pthread_cancel(thread[j]);
}
}
break;
}
if(ntries0 == 0)
{
h++;
/*线程阻塞,其他线程争夺资源,或者是等待pthread_cancel函数发送cancel信号终止线程*/
pthread_testcancel();
/*这是为了弄明白pthread_testcancel函数的作用而设置的代码段*/
if(h == 10000)
{
h = 0;
printf("----------thread num %lx-------------\n",tid);
}
}
}
pthread_cleanup_pop(0);
return (void *)0;
}
int main()
{
int i,pid;
pid = getpid(); //设置要查找的数
pthread_mutex_init(&mutex,NULL);
printf("Search the num of %d\n",pid);
for(started = 0; started < THREAD_MAX; started++)
{
pthread_create(&thread[started],NULL,(void *)Search_Num,(void *)pid);
}
for(i = 0; i < THREAD_MAX; i++)
{
printf("-----------i = %d--------------\n",i);
pthread_join(thread[i],NULL);
}
printf("It took %d tries ot find the number!\n",tries);
return 0;
}
Search the num of 6531 -----------i = 0-------------- thread num b6fbcb70 thread num b67bbb70 thread num b5fbab70 thread num b77bdb70 ----------thread num b67bbb70------------- Thread b67bbb70 found the number! ----------thread num b6fbcb70------------- ----------thread num b77bdb70------------- ----------2busy2----------- ----------thread num b5fbab70------------- ----------2busy2----------- Thread b5fbab70 was canceled on its 1174527 try. Thread b77bdb70 was canceled on its 1023100 try. -----------i = 1-------------- Thread b6fbcb70 was canceled on its 1174527 try. -----------i = 2-------------- -----------i = 3-------------- It took 1174527 tries ot find the number!
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有