1 Star 0 Fork 0

散漫小主 / NetworkProgramming

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
condtest.cpp 2.11 KB
一键复制 编辑 原始数据 按行查看 历史
Idiot 提交于 2019-08-15 20:27 . p41 线程池的实现[未完]
//
// Created by jxq on 19-8-15.
//
// p39 posix信号量与互斥锁
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <pthread.h>
using namespace std;
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0);
#define CONSUMERS_COUNT 1
#define PRODUCERS_COUNT 1
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
pthread_t g_thread[CONSUMERS_COUNT + PRODUCERS_COUNT];
int ready = 0;
void *produce (void *arg)
{
int num = *((int *)arg);
int i;
while (1)
{
printf("%d produce is waiting\n", num);
pthread_mutex_lock(&g_mutex);
printf("%d produce begin produce product %d\n", num, ready);
while (ready == 0)
{
pthread_cond_wait(&g_cond, &g_mutex);
}
printf("%d produce end produce product %d\n", num, ready++);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
void *consume (void *arg)
{
int num = *((int *)arg);
int i;
while (1)
{
printf("%d consume is waiting\n", num);
pthread_mutex_lock(&g_mutex);
printf("%d consume begin consume product %d\n", num, ready);
++ready;
pthread_cond_signal(&g_cond);
printf("%d consume end consume product %d\n", num, ready);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
int main(int argc, char** argv)
{
pthread_mutex_init(&g_mutex, NULL);
pthread_cond_init(&g_cond, NULL);
int i;
for (i = 0; i < CONSUMERS_COUNT; ++i)
{
pthread_create(&g_thread[i], NULL, consume, &i);
}
sleep(1);
for (i = 0; i < PRODUCERS_COUNT; ++i)
{
pthread_create(&g_thread[CONSUMERS_COUNT+i], NULL, produce, &i);
}
for (i = 0; i < CONSUMERS_COUNT + PRODUCERS_COUNT; ++i)
{
pthread_join(g_thread[i], NULL);
}
pthread_mutex_destroy(&g_mutex);
pthread_cond_destroy(&g_cond);
return 0;
}
1
https://gitee.com/YuXiaoXiang_930/NetworkProgramming.git
git@gitee.com:YuXiaoXiang_930/NetworkProgramming.git
YuXiaoXiang_930
NetworkProgramming
NetworkProgramming
master

搜索帮助