1 Star 0 Fork 0

fortianyang/StudyForLinux

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
testMain.cc 1.62 KB
一键复制 编辑 原始数据 按行查看 历史
fortianyang 提交于 2023-08-20 11:36 +08:00 . 信号量的学习代码
#include "ringQueue.hpp"
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
void *consumer(void *args)
{
RingQueue<int> *rq = (RingQueue<int> *)args;
while (true)
{
int x;
rq->pop(&x);
//std::cout << "消费: " << x << std::endl;
std::cout << "消费: " << x ;
std::cout<<" [" << pthread_self() << "]" << std::endl;
sleep(1);
}
}
void *productor(void *args)
{
RingQueue<int> *rq = (RingQueue<int> *)args;
while (true)
{
int x = rand() % 100 + 1;
// std::cout << "生产: " << x << std::endl;
std::cout << "生产: " << x ;
std::cout<< " [" << pthread_self() << "]" << std::endl;
rq->push(x);
}
}
// 单线程版本
// int main()
// {
// RingQueue<int> *rq = new RingQueue<int>();
// pthread_t c, p;
// pthread_create(&c, nullptr, consumer, (void *)rq);
// pthread_create(&p, nullptr, productor, (void *)rq);
// pthread_join(c, nullptr);
// pthread_join(p, nullptr);
// return 0;
// }
//多线程版本
int main()
{
srand((uint64_t)time(nullptr) ^ getpid());
RingQueue<int> *rq = new RingQueue<int>();
// rq->debug();
pthread_t c[3],p[2];
pthread_create(c, nullptr, consumer, (void*)rq);
pthread_create(c+1, nullptr, consumer, (void*)rq);
pthread_create(c+2, nullptr, consumer, (void*)rq);
pthread_create(p, nullptr, productor, (void*)rq);
pthread_create(p+1, nullptr, productor, (void*)rq);
for(int i = 0; i < 3; i++) pthread_join(c[i], nullptr);
for(int i = 0; i < 2; i++) pthread_join(p[i], nullptr);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fortianyang/study-for-network.git
git@gitee.com:fortianyang/study-for-network.git
fortianyang
study-for-network
StudyForLinux
master

搜索帮助