멀티 프로듀서와 소비자가있는 코드를 만들려고했습니다. 나는 생산자와 소비자를 위해 다중 스레드를 만들고 동기화를 위해 세마포어를 사용했다. 이 코드는 단일 제작자와 소비자가 잘 작동했습니다.멀티 프로듀서 - 소비자 실행의 효율성
제가 직면 한 문제는 프로그램 실행 시간이 지나면 consumer1과 producer1 만 프로세스에 참여한다는 것입니다. 나는 다른 생산자와 소비자에게 무슨 일이 일어 났는지 이해할 수 없다.
멀티 프로듀서 - 소비자 문제를 효율적으로 만드는 방법을 알고 싶습니다. 모든 생산자와 소비자가 각각 생산하고 소비 할 동등한 기회를 얻는다는 의미에서 효율적입니까? C++ 코드는 (그것은 C를 많이 포함) :
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <queue>
using namespace std;
sem_t empty;
sem_t full;
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
queue<int> q;
void *producer(void *a)
{
int *num = (int *)a;
while(1) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
cnt = cnt+1;
q.push(cnt);
cout<<cnt<<" item produced by producer "<<(*num+1)<<endl;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
}
void *consumer(void *a)
{
int *num = (int *)a;
while(1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
cout<<q.front()<<" item consumed by consumer "<<(*num+1)<<endl;
q.pop();
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
}
int main()
{
pthread_t p[5];
pthread_t c[5];
sem_init(&empty,0,5);
sem_init(&full,0,0);
int i;
for(i = 0; i < 5; i++) {
pthread_create(&p[i],NULL,producer,(void *)(&i));
}
for(i = 0; i < 5; i++) {
pthread_create(&c[i],NULL,consumer,(void *)(&i));
}
for(i = 0; i < 5; i++) {
pthread_join(p[i],NULL);
pthread_join(c[i],NULL);
}
}
업데이트 코드 :
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <queue>
#include <map>
using namespace std;
sem_t empty;
sem_t full;
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
map<pthread_t,int> mc,mp;
queue<int> q;
void *producer(void *a)
{
while(1) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
cnt = cnt+1;
q.push(cnt);
cout<<cnt<<" item produced by producer "<<mp[pthread_self()]<<endl;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
}
void *consumer(void *a)
{
while(1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
cout<<q.front()<<" item consumed by consumer "<<mc[pthread_self()]<<endl;
q.pop();
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
}
int main()
{
pthread_t p[5];
pthread_t c[5];
sem_init(&empty,0,5);
sem_init(&full,0,0);
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < 5; i++) {
pthread_create(&p[i],NULL,producer,NULL);
pthread_create(&c[i],NULL,consumer,NULL);
mc[c[i]] = i+1;
mp[p[i]] = i+1;
}
pthread_mutex_unlock(&mutex);
for(i = 0; i < 5; i++) {
pthread_join(p[i],NULL);
pthread_join(c[i],NULL);
}
}
pthread_create에 전달할 인수를 살펴보고 스레드 함수에서 해당 정보를 사용하는 방법을 살펴보십시오. 경쟁 조건이 있는지 고려하십시오. 'i'를 전달할 때와 'i'를 전달할 때의 영향을 고려하십시오. –
표준'std :: thread' 대신 OS 특정'pthread' 사용을 정당화하는 이유는 무엇입니까? – Christophe
@Christophe : C++로 쓰레드를 배웠던 적이 없기 때문에 C 버전을 사용했습니다. –