c语言取消线程例程函数 c语言关闭程序代码

C语言如何终止线程?

面只有两个线程,是生产者/消费者模式,已编译通过,注释很详细。

10多年的贵溪网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整贵溪建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“贵溪网站设计”,“贵溪网站推广”以来,每个客户项目都认真落实执行。

/* 以生产者和消费者模型问题来阐述Linux线程的控制和通信你

生产者线程将生产的产品送入缓冲区,消费者线程则从中取出产品。

缓冲区有N个,是一个环形的缓冲池。

*/

#include stdio.h

#include pthread.h

#define BUFFER_SIZE 16

struct prodcons

{

int buffer[BUFFER_SIZE];/*实际存放数据的数组*/

pthread_mutex_t lock;/*互斥体lock,用于对缓冲区的互斥操作*/

int readpos,writepos; /*读写指针*/

pthread_cond_t notempty;/*缓冲区非空的条件变量*/

pthread_cond_t notfull;/*缓冲区未满 的条件变量*/

};

/*初始化缓冲区*/

void pthread_init( struct prodcons *p)

{

pthread_mutex_init(p-lock,NULL);

pthread_cond_init(p-notempty,NULL);

pthread_cond_init(p-notfull,NULL);

p-readpos = 0;

p-writepos = 0;

}

/*将产品放入缓冲区,这里是存入一个整数*/

void put(struct prodcons *p,int data)

{

pthread_mutex_lock(p-lock);

/*等待缓冲区未满*/

if((p-writepos +1)%BUFFER_SIZE ==p-readpos)

{

pthread_cond_wait(p-notfull,p-lock);

}

p-buffer[p-writepos] =data;

p-writepos++;

if(p-writepos = BUFFER_SIZE)

p-writepos = 0;

pthread_cond_signal(p-notempty);

pthread_mutex_unlock(p-lock);

}

/*从缓冲区取出整数*/

int get(struct prodcons *p)

{

int data;

pthread_mutex_lock(p-lock);

/*等待缓冲区非空*/

if(p-writepos == p-readpos)

{

pthread_cond_wait(p-notempty ,p-lock);//非空就设置条件变量notempty

}

/*读书据,移动读指针*/

data = p-buffer[p-readpos];

p-readpos++;

if(p-readpos == BUFFER_SIZE)

p-readpos = 0;

/*设置缓冲区未满的条件变量*/

pthread_cond_signal(p-notfull);

pthread_mutex_unlock(p-lock);

return data;

}

/*测试:生产站线程将1 到1000的整数送入缓冲区,消费者线程从缓冲区中获取整数,两者都打印信息*/

#define OVER (-1)

struct prodcons buffer;

void *producer(void *data)

{

int n;

for( n=0;n1000;n++)

{

printf("%d ------\n",n);

put(buffer,n);

}

put(buffer,OVER);

return NULL;

}

void *consumer(void *data)

{

int d;

while(1)

{

d = get(buffer);

if(d == OVER)

break;

else

printf("-----%d\n",d);

}

return NULL;

}

int main()

{

pthread_t th_p,th_c;

void *retval;

pthread_init(buffer);

pthread_create(th_p,NULL,producer,0);

pthread_create(th_c,NULL,consumer,0);

/*等待两个线程结束*/

pthread_join(th_p, retval);

pthread_join(th_c,retval);

return 0;

}

C语言如何让结束指定进程中的指定线程

终止线程有三种方法:

1.线程可以在自身内部调用AfxEndThread()来终止自身的运行

2.可以在线程的外部调用BOOL TerminateThread( HANDLE hThread, DWORD dwExitCode )来强行终止一个线程的运行,

然后调用CloseHandle()函数释放线程所占用的堆栈

3.第三种方法是改变全局变量,使线程的执行函数返回,则该线程终止。

unsigned long __cdecl _beginthread (void (__cdecl *) (void *),

unsigned, void *); PS--这是我复制的别人的

C语言 杀死线程 Api函数

GetExitCodeThread函数可以得到线程终结时的返回值,因为线程终结了,所以系统中不再有这个线程,hThreadRcvData本身已经无效,所以调用TerminateThread函数会失败。

网站栏目:c语言取消线程例程函数 c语言关闭程序代码
网站链接:https://www.cdcxhl.com/article6/dddjeig.html

成都网站建设公司_创新互联,为您提供网站导航服务器托管网站建设ChatGPT标签优化用户体验

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设公司