c语言如何编写一个简单的多线程程序?

c语言如何编写一个简单的多线程程序?,第1张

这是一个多线程例子,里面只有两个线程,是生产者/消费者模式,已编译通过,注释很详细,\x0d\x0a如下:\x0d\x0a\x0d\x0a/* 以生产者和消费者模型问题来阐述Linux线程的控制和通信你 \x0d\x0a生产者线程将生产的产品送入缓冲区,消费者线程则从中取出产品。\x0d\x0a缓冲区有N个,是一个环形的缓冲池。\x0d\x0a*/\x0d\x0a#include \x0d\x0a#include \x0d\x0a\x0d\x0a#define BUFFER_SIZE 16\x0d\x0a\x0d\x0astruct prodcons\x0d\x0a{\x0d\x0aint buffer[BUFFER_SIZE]/*实际存放数据的数组*/\x0d\x0apthread_mutex_t lock/*互斥体lock,用于对缓冲区的互斥 *** 作*/\x0d\x0aint readpos,writepos/*读写指针*/\x0d\x0apthread_cond_t notempty/*缓冲区非空的条件变量*/\x0d\x0apthread_cond_t notfull/*缓冲区未满 的条件变量*/\x0d\x0a}\x0d\x0a\x0d\x0a/*初始化缓冲区*/\x0d\x0avoid pthread_init( struct prodcons *p)\x0d\x0a{\x0d\x0apthread_mutex_init(&p->lock,NULL)\x0d\x0apthread_cond_init(&p->notempty,NULL)\x0d\x0apthread_cond_init(&p->notfull,NULL)\x0d\x0ap->readpos = 0\x0d\x0ap->writepos = 0\x0d\x0a}\x0d\x0a\x0d\x0a/*将产品放入缓冲区,这里是存入一个整数*/\x0d\x0avoid put(struct prodcons *p,int data)\x0d\x0a{\x0d\x0apthread_mutex_lock(&p->lock)\x0d\x0a/*等待缓冲区未满*/\x0d\x0aif((p->writepos +1)%BUFFER_SIZE ==p->readpos)\x0d\x0a{\x0d\x0apthread_cond_wait(&p->notfull,&p->lock)\x0d\x0a}\x0d\x0ap->buffer[p->writepos] =data\x0d\x0ap->writepos++\x0d\x0aif(p->writepos >= BUFFER_SIZE)\x0d\x0ap->writepos = 0\x0d\x0apthread_cond_signal(&p->notempty)\x0d\x0apthread_mutex_unlock(&p->lock)\x0d\x0a}\x0d\x0a/*从缓冲区取出整数*/\x0d\x0aint get(struct prodcons *p)\x0d\x0a{\x0d\x0aint data\x0d\x0apthread_mutex_lock(&p->lock)\x0d\x0a/*等待缓冲区非空*/\x0d\x0aif(p->writepos == p->readpos)\x0d\x0a{\x0d\x0apthread_cond_wait(&p->notempty ,&p->lock)//非空就设置条件变量notempty\x0d\x0a}\x0d\x0a/*读书据,移动读指针*/\x0d\x0adata = p->buffer[p->readpos]\x0d\x0ap->readpos++\x0d\x0aif(p->readpos == BUFFER_SIZE)\x0d\x0ap->readpos = 0\x0d\x0a/*设置缓冲区未满的条件变量*/\x0d\x0apthread_cond_signal(&p->notfull)\x0d\x0apthread_mutex_unlock(&p->lock)\x0d\x0areturn data\x0d\x0a}\x0d\x0a /*测试:生产站线程将1 到1000的整数送入缓冲区,消费者线程从缓冲区中获取整数,两者都打印信息*/\x0d\x0a#define OVER (-1)\x0d\x0astruct prodcons buffer\x0d\x0avoid *producer(void *data)\x0d\x0a{\x0d\x0aint n\x0d\x0afor( n=0n\n",n)\x0d\x0aput(&buffer,n)\x0d\x0a}\x0d\x0aput(&buffer,OVER)\x0d\x0areturn NULL\x0d\x0a}\x0d\x0avoid *consumer(void *data)\x0d\x0a{\x0d\x0aint d\x0d\x0awhile(1)\x0d\x0a{\x0d\x0ad = get(&buffer)\x0d\x0aif(d == OVER)\x0d\x0abreak\x0d\x0aelse\x0d\x0aprintf("----->%d\n",d)\x0d\x0a}\x0d\x0areturn NULL\x0d\x0a}\x0d\x0aint main()\x0d\x0a{\x0d\x0apthread_t th_p,th_c\x0d\x0avoid *retval\x0d\x0a pthread_init(&buffer)\x0d\x0apthread_create(&th_p,NULL,producer,0)\x0d\x0apthread_create(&th_c,NULL,consumer,0)\x0d\x0a/*等待两个线程结束*/\x0d\x0a pthread_join(th_p, &retval)\x0d\x0a pthread_join(th_c,&retval)\x0d\x0a return 0\x0d\x0a}

thread_creation.c

gcc thread_creation.c

会在当前目录下,生成可执行的a.out文件

./a.out


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/10875140.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-11
下一篇 2023-05-11

发表评论

登录后才能评论

评论列表(0条)

保存