gpt4 book ai didi

c++ - 无限循环多线程

转载 作者:行者123 更新时间:2023-11-28 05:49:48 24 4
gpt4 key购买 nike

我已经编写了这个生产者/消费者问题解决方案。它似乎在工作,除了无限循环。我的印象是 pthread_exit(NULL); 会让它停止,但老实说,我已经迷失和困惑了。有人可以指出如何停止循环的正确方向吗?

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<iostream>
#include<semaphore.h>

#define BUFFSIZE 10

using namespace std;

int buffer[BUFFSIZE];
int size; //current buffer size
int n = 0, m = 0;

pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;

sem_t Available;
sem_t Buffer; //indicates if buffer is full

//----------------------------------------------------------------//

void *Consumers(void *argument)
{
int con_id = *((int *) argument);
while(1)
{
if(size == 0)
{
cout << "Queue is empty." << endl;
}

sem_wait(&Available);
pthread_mutex_lock(&Mutex);

size--;
cout << "Con " << con_id << ": Product removed from buffer" << endl;
//for(int i = 0; i < size; i++)
//{
// cout << Buffer[i] << " ";
//}
cout << endl;
pthread_mutex_unlock(&Mutex);
sem_post(&Buffer);
}
return(NULL);
}

//----------------------------------------------------------------//

void *Producers(void *argument)
{
int item = 8;
int pro_id = *((int *) argument);

while(1)
{
sem_wait(&Buffer);
pthread_mutex_lock(&Mutex);
//Buffer[size] = item;
cout << "Item added" << endl;
size++;
pthread_mutex_unlock(&Mutex);
sem_post(&Available);
}
return(NULL);
}

//----------------------------------------------------------------//

int main()
{

cout << "Enter number of producers: " << endl;
scanf("%d", &n);
cout << "Enter number of consumers: " << endl;
scanf("%d", &m);
//get number of producers(int n), and consumers(int m)
sem_init(&Available, 0, 0);
sem_init(&Buffer, 0, BUFFSIZE);

pthread_t *con = new pthread_t[m];
int *thread_args_c = new int[m];
for(int i = 0; i < n; i++)
{
thread_args_c[i] = i;
pthread_create(&con[i], NULL, Consumers, (void*) &i);
}

pthread_t *pro = new pthread_t[n];
int *thread_args_p = new int[n];
for(int i = 0; i < n; i++)
{
thread_args_p[i] = i;
pthread_create(&pro[i], NULL, Producers, (void*) &i);
pthread_join(con[i], NULL);
}

pthread_exit(NULL);

}

最佳答案

不确定您的期望是什么。 pthread_exit 出现在 main 的末尾(并且在那里完全不需要,因为 main 无论如何都会退出),但是线程内的无限循环永远不会让 main 到达这一点(因为您正在加入消费者线程).

此外,您的创建和加入模型毫无意义 - 在您创建生产者之后加入消费者线程有什么意义?

最后,但不是租约,您无法加入生产者线程。

关于c++ - 无限循环多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35511432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com