无限循环多线程
问题描述:
我已经写了这个生产者/消费者问题的解决方案。它似乎在工作,除了无限循环之外。我的印象是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达到这一点(因为你正在加入消费者线程)。
此外,您的创建和连接模型让人感觉不错 - 创建生产者后加入消费者线程有什么意义?
最后,但没有租约,您无法加入生产者线程。
答
循环不会停止,因为代码中没有逻辑来实际退出循环。
由于pthread_join
暂停线程调用线程直到目标退出,因此进程停滞不前。请参阅documentation for pthread_join
如果您不关心实际终止线程并返回到主线程,只需将呼叫移除到pthread_join
即可。该进程应该因为主线程退出而终止。
要真正地正确终止循环,您需要设置内部或外部触发器。经过一系列迭代后,您可以在内部让循环退出。为此,您将执行while(x<=y)
而不是while(1)
。
你也可以让它更加复杂一点,并让主线程向外部发出其他线程的信号,以便让其他线程关闭。你可以让主线程设置一个(volatile
)布尔值,当你准备好退出并且让其他线程break
成为基于它的循环时。如果您关心退出的Atomicity,则需要使用锁来保护布尔值。
main()'int i'变量的数据竞争,其地址传递给从它们读取的线程,而main()'修改它们。另外''i'在我的生命周期结束后使用。 – EOF