Producer-Consumer Issue - c++

Hi I'm trying to write an algorithm for solving the producer-consumer problem and I've hit a roadblock. This is the output I am getting from my code:
Producing: 6
6 0 0 0 0 0 0 0 0 0 END
and then the program exits. I'm not sure where I went wrong? Did I do something wrong in creating a circular buffer?
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;
#define BUFFER_SIZE 10
void *produce(void *);
void *consume(void *);
int produceItem(void);
void insertItem(int item);
void removeItem(void);
void printBuffer(void);
int head = 0;
int tail = 0;
int item;
int bufferCount = 0;
pthread_t producer, consumer;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock;
sem_t sem_filledSlots;
sem_t sem_emptySlots;
int buffer[BUFFER_SIZE];
int main() {
int emptyCount;
int item;
srand (time(NULL));
sem_init(&sem_filledSlots, 0, 0);
sem_init(&sem_emptySlots, 0, BUFFER_SIZE);
sem_getvalue(&sem_emptySlots, &emptyCount);
pthread_create (&producer, NULL, &produce, NULL);
pthread_create (&consumer, NULL, &consume, NULL);
return 0;
}
void *produce(void *)
{
for(int i = 0; i <15; i++)
{
item = produceItem();
sem_wait(&sem_emptySlots);
pthread_mutex_lock(&lock);
printf("Producing: %d \n", item);
buffer[head] = item;
head = (head + 1) % BUFFER_SIZE;
printBuffer();
pthread_mutex_unlock(&lock);
sem_post(&sem_filledSlots);
}
}
void *consume(void *)
{
for(int i = 0; i <15; i++)
{
sem_wait(&sem_filledSlots);
pthread_mutex_lock(&lock);
printf("Consuming %d \n", buffer[tail]);
buffer[tail] = 0;
tail = (tail + 1) % BUFFER_SIZE;
bufferCount--;
printBuffer();
pthread_mutex_unlock(&lock);
sem_post(&sem_emptySlots);
}
}
int produceItem(void)
{
int x = (rand()%11 + 1);
return x;
}
void printBuffer(void)
{
for(int i = 0; i <BUFFER_SIZE; i++)
{
printf("%d ", buffer[i]);
}
printf("END \n");
}

you're missing pthread_join before exiting the program:
....
pthread_join(producer,NULL);
pthread_join(consumer,NULL);
return 0;
....

Related

C/C++ threads magic difference in condition

I wanted to write simple multithread app in C/C++. Function funProducent produces 100 values and if random generated value is in given range, char is added to buffer. Function funKonzument comsumes values from buffer. Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define BUFFER_LIMIT 20
struct struktura{
pthread_mutex_t mutex;
pthread_cond_t bufferNotFull;
pthread_cond_t bufferNotEmpty;
int bufferIndex;
char * buffer;
int junk;
};
void * funProducent(void *arg){
struktura * data = (struktura *) arg;
int i = 0;
while (i < 100) {
pthread_mutex_lock(&data->mutex);
if(data->bufferIndex == BUFFER_LIMIT - 1){
pthread_cond_wait(&data->bufferNotFull, &data->mutex);
}
int randomValue = (rand() % 20) + 1;
if( randomValue < 13 ){
data->buffer[++data->bufferIndex] = 'a';
printf("%2d : Producent at index %d added %c\n", i, data->bufferIndex, data->buffer[data->bufferIndex]);
pthread_cond_signal(&data->bufferNotEmpty);
} else {
data->junk++;
}
pthread_mutex_unlock(&data->mutex);
i++;
}
printf("producent is done\n");
}
void * funKonzument(void *arg){
struktura * data = (struktura *) arg;
int i = 0;
while (i + data->junk < 100) {
printf("%d\n", i + data->junk);
pthread_mutex_lock(&data->mutex);
if(data->bufferIndex < 0){
pthread_cond_wait(&data->bufferNotEmpty, &data->mutex);
}
printf("%2d : Konzument at index %d consumed %c\n", i, data->bufferIndex, data->buffer[data->bufferIndex]);
data->bufferIndex--;
pthread_cond_signal(&data->bufferNotFull);
pthread_mutex_unlock(&data->mutex);
i++;
}
printf("konzument is done\n");
}
int main(int argc, char** argv) {
pthread_t threadProducent, threadKonzument;
struktura threadData;
threadData.buffer = (char *) malloc(sizeof(char) * BUFFER_LIMIT);
threadData.bufferIndex = -1;
threadData.bufferNotFull = PTHREAD_COND_INITIALIZER;
threadData.bufferNotEmpty = PTHREAD_COND_INITIALIZER;
threadData.mutex = PTHREAD_MUTEX_INITIALIZER;
threadData.junk = 0;
pthread_create(&threadProducent, NULL, funProducent, &threadData);
pthread_create(&threadKonzument, NULL, funKonzument, &threadData);
pthread_join(threadProducent, NULL);
pthread_join(threadKonzument, NULL);
free(threadData.buffer);
pthread_mutex_destroy(&threadData.mutex);
pthread_cond_destroy(&threadData.bufferNotFull);
pthread_cond_destroy(&threadData.bufferNotEmpty);
return 0;
}
When I try to run this code, sometimes it stucks in funKonzument at this line:
pthread_cond_wait(&data->bufferNotEmpty, &data->mutex);
But...when I change condition in funProducent method from:
if( randomValue < 13 )
to
if( randomValue > 8 )
everything works fine. Is anyone able to explain me what magic difference is between this two conditions?
You are probably suffering from spurious wakes and some problem with the junk counter. I just removed that counter and added a cond wait loop function (and a little lock context manager) and then the hangings seems to have stopped.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <stdexcept>
#include <functional>
#define BUFFER_LIMIT 20
struct struktura{
pthread_mutex_t mutex;
pthread_cond_t bufferNotFull;
pthread_cond_t bufferNotEmpty;
int bufferIndex;
char * buffer;
};
// a lock context manager
class mlock {
pthread_mutex_t* mtx;
public:
mlock(pthread_mutex_t& Mtx) :
mtx(&Mtx)
{
int rv=pthread_mutex_lock(mtx);
if(rv) throw std::runtime_error(std::to_string(rv));
}
mlock(const mlock&) = delete;
mlock(mlock&&) = delete;
mlock& operator=(const mlock&) = delete;
mlock& operator=(mlock&&) = delete;
~mlock() {
pthread_mutex_unlock(mtx);
}
};
// silly loop to take care of spurious wakes
void cwait(pthread_cond_t& c, pthread_mutex_t& m, std::function<bool()> f) {
while(f()) pthread_cond_wait(&c, &m);
}
void* funProducent(void *arg){
struktura* data = static_cast<struktura*>(arg);
int i = 0;
while(i < 100) {
mlock dummy(data->mutex);
cwait(data->bufferNotFull, data->mutex, [&](){return data->bufferIndex == BUFFER_LIMIT - 1;});
int randomValue = (rand() % 20) + 1;
if( randomValue < 13 ){
data->buffer[++data->bufferIndex] = 'a';
printf("%2d : Producent at index %d added %c\n", i, data->bufferIndex, data->buffer[data->bufferIndex]);
i++;
pthread_cond_signal(&data->bufferNotEmpty);
}
}
printf("producent is done\n");
return nullptr;
}
void* funKonzument(void *arg){
struktura* data = static_cast<struktura*>(arg);
int i = 0;
while(i < 100) {
mlock dummy(data->mutex);
cwait(data->bufferNotEmpty, data->mutex, [&](){return data->bufferIndex<0;});
printf("\t\t\t%2d : Konzument at index %d consumed %c\n", i, data->bufferIndex, data->buffer[data->bufferIndex]);
data->bufferIndex--;
i++;
pthread_cond_signal(&data->bufferNotFull);
}
printf("\t\t\tkonzument is done\n");
return nullptr;
}
int main() {
pthread_t threadProducent, threadKonzument;
struktura threadData;
threadData.buffer = (char *) malloc(sizeof(char) * BUFFER_LIMIT);
threadData.bufferIndex = -1;
threadData.bufferNotFull = PTHREAD_COND_INITIALIZER;
threadData.bufferNotEmpty = PTHREAD_COND_INITIALIZER;
threadData.mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_create(&threadProducent, NULL, funProducent, &threadData);
pthread_create(&threadKonzument, NULL, funKonzument, &threadData);
pthread_join(threadProducent, NULL);
pthread_join(threadKonzument, NULL);
free(threadData.buffer);
pthread_mutex_destroy(&threadData.mutex);
pthread_cond_destroy(&threadData.bufferNotFull);
pthread_cond_destroy(&threadData.bufferNotEmpty);
return 0;
}

How to avoid global semaphores and queues when using threads

I have a problem with my code. It works, but I cannot avoid using global semaphores. I have 3 thread functions. the first is run by 10 threads. The second and third are run by 2 threads each. These threads should run without having race conditions. In addition, they should communicate with each other. I use a user defined queue class for communications between threads and between the threads and main. Also, I use the semaphores to achieve mutual exclusion between the threads. Since I declare the instance of the queue class and the semaphores in a global manner, I do not have to pass them to any function. They are accessible to any function in this program. However, this is not a healthy way to write programs. Therefore, I ask you, how to declare the queue and the semaphores locally, and what is the best way to pass them between threads.
// queueString header
#include <string>
#include <queue>
#include <semaphore.h>
using namespace std;
class queueString
{
public:
queueString();
~queueString();
void qPush(string str);
string qPop();
private:
sem_t queueSem;
queue <string> q;
};
//queueString class
#include "queueString.h"
using namespace std;
// queue class that will enqueue and dequeue atomically.
queueString::queueString(){
sem_init(&queueSem, 0, 1);
}
queueString::~queueString(){}
void queueString::qPush(string str){
sem_wait(&queueSem);
this->q.push(str);
sem_post(&queueSem);
}
string queueString::qPop(){
sem_wait(&queueSem);
string str = this->q.front();
q.pop();
sem_post(&queueSem);
return str;
}
//The three threads with main
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
#include "queueString.h"
using namespace std;
//My question is here, How to declare the variables below locally, and where
// is the right place to declare them, and how to pass them to threads?
sem_t s12, s13, s21, s31, sthr1, sthr2[2], sthr3[2], printSem;
sem_t idInitializationSemMainToThread, idInitializationSemThreadToMain;
queueString q = queueString();
#define THR1NUM 10
#define THR2NUM 2
#define THR3NUM 2
void printString(string str);
void *thread1(void* arg){
sem_wait(&idInitializationSemMainToThread);
int *pnum = (int *)arg;
int thr_1_ID = *pnum;
sem_post(&idInitializationSemThreadToMain);
sem_wait(&sthr1);
string value= "THR1 ";
value.append(to_string(thr_1_ID));
q.qPush(value);
sem_post(&s12);
sem_wait(&s21);
value= "2nd Iteration THR1 ";
value.append(to_string(thr_1_ID));
q.qPush(value);
sem_post(&s13);
sem_wait(&s31);
sem_post(&sthr1);
}
void *thread2(void* arg){
sem_wait(&idInitializationSemMainToThread);
int *pnum = (int *)arg;
int thr_2_ID = *pnum;
sem_post(&idInitializationSemThreadToMain);
while (true)
{
sem_wait(&sthr2[thr_2_ID]);
sem_wait(&s12);
string readVal = q.qPop();
printString(readVal + ", THR2 "+ to_string(thr_2_ID));
if (thr_2_ID==0)
sem_post(&sthr2[1]);
else
sem_post(&sthr2[0]);
sem_post(&s21);
}
}
void *thread3(void* arg){
sem_wait(&idInitializationSemMainToThread);
int *pnum = (int *)arg;
int thr_3_ID = *pnum;
sem_post(&idInitializationSemThreadToMain);
while (true)
{
sem_wait(&sthr3[thr_3_ID]);
sem_wait(&s13);
string readVal = q.qPop();
printString(readVal + " THR3 " + to_string(thr_3_ID));
if (thr_3_ID == 0)
sem_post(&sthr3[1]);
else
sem_post(&sthr3[0]);
sem_post(&s31);
}
}
int main(){
pthread_t thr1[THR1NUM], thr2[THR2NUM], thr3[THR3NUM];
sem_init(&s12, 0, 0);
sem_init(&s13, 0, 0);
sem_init(&s31, 0, 0);
sem_init(&s21, 0, 0);
sem_init(&printSem, 0, 1);
sem_init(&sthr1, 0, 0);
for (int i = 0; i < 2;i++)
sem_init(&sthr2[i], 0, 0);
for (int i = 0; i < 2;i++)
sem_init(&sthr3[i], 0, 0);
sem_init(&idInitializationSemMainToThread, 0, 0);
sem_init(&idInitializationSemThreadToMain, 0, 0);
int *pnum =(int *) malloc(sizeof(int));
for (int j = 0; j < THR2NUM;j++){
*pnum = j;
pthread_create(&thr2[j], NULL, thread2, (void *)pnum);
sem_post(&idInitializationSemMainToThread);
printString("thr2 "+to_string(j)+ " created");
sem_wait(&idInitializationSemThreadToMain);
}
for (int k = 0; k < THR3NUM;k++){
*pnum = k;
pthread_create(&thr3[k], NULL, thread3,(void *) pnum);
sem_post(&idInitializationSemMainToThread);
printString("thr3 "+to_string(k)+ " created");
sem_wait(&idInitializationSemThreadToMain);
}
for (int i = 0; i < THR1NUM;i++){
*pnum = i;
pthread_create(&thr1[i], NULL, thread1,(void *) pnum);
sem_post(&idInitializationSemMainToThread);
printString("thr1 "+to_string(i)+ " created");
sem_wait(&idInitializationSemThreadToMain);
}
sem_post(&sthr2[0]);
sem_post(&sthr3[0]);
sem_post(&sthr1);
for (int i = 0; i < THR1NUM;i++){
pthread_join(thr1[i], NULL);
printString("thr1 "+to_string(i)+ " joined");
}
for (int i = 0; i < THR2NUM; i++){
pthread_cancel(thr2[i]);
printString("thr2 "+to_string(i)+ " exited");
}
for (int i = 0; i < THR3NUM;i++){
pthread_cancel(thr3[i]);
printString("thr3 "+to_string(i)+ " exited");
sem_post(&printSem);
}
sem_destroy(&s12);
sem_destroy(&s21);
sem_destroy(&s13);
sem_destroy(&s31);
sem_destroy(&sthr1);
free(pnum);
}
// function to print strings atomically.
void printString(string str){
sem_wait(&printSem);
printf("%s\n", str.c_str());
sem_post(&printSem);
}

Pthreads pool, keeping 1000 opened threads, pthread_create() returns 11

Need some help with PTHREADS. I want to keep over 1000 threads opened at any time, something like a thread pool. Here is the code :
/*
gcc -o test2 test2.cpp -static -lpthread -lstdc++
*/
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <stdexcept>
#include <cstdlib>
int NUM_THREADS = 2000;
int MAX_THREADS = 100;
int THREADSTACK = 65536;
struct thread_struct{
int arg1;
int arg2;
};
pthread_mutex_t mutex_;
static unsigned int thread_count = 0;
string exec(const char* cmd)
{
int DEBUG=0;
char buffer[5000];
string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe && DEBUG) throw runtime_error("popen() failed!");
try
{
while (!feof(pipe))
{
if (fgets(buffer, 128, pipe) != NULL)
{
result += buffer;
}
}
}
catch(...)
{
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
void *thread_test(void *arguments)
{
pthread_mutex_lock(&mutex_);
thread_count++;
pthread_mutex_unlock(&mutex_);
// long tid;
// tid = (long)threadid;
struct thread_struct *args = (thread_struct*)arguments;
/*
printf("ARG1=%d\n",args->arg1);
printf("ARG2=%d\n",args->arg2);
*/
int thread_id = (int) args->arg1;
/*
int random_sleep;
random_sleep = rand() % 10 + 1;
printf ("RAND=[%d]\n", random_sleep);
sleep(random_sleep);
*/
int random_sleep;
random_sleep = rand() % 10 + 5;
// printf ("RAND=[%d]\n", random_sleep);
char command[100];
memset(command,0,sizeof(command));
sprintf(command,"sleep %d",random_sleep);
exec(command);
random_sleep = rand() % 100000 + 500000;
usleep(random_sleep);
// simulation of a work between 5 and 10 seconds
// sleep(random_sleep);
// printf("#%d -> sleep=%d total_threads=%u\n",thread_id,random_sleep,thread_count);
pthread_mutex_lock(&mutex_);
thread_count--;
pthread_mutex_unlock(&mutex_);
pthread_exit(NULL);
}
int main()
{
// pthread_t threads[NUM_THREADS];
int rc;
int i;
usleep(10000);
srand ((unsigned)time(NULL));
unsigned int thread_count_now = 0;
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, THREADSTACK);
pthread_mutex_init(&mutex_, NULL);
for( i=0; i < NUM_THREADS; i++ )
{
create_thread:
pthread_mutex_lock(&mutex_);
thread_count_now = thread_count;
pthread_mutex_unlock(&mutex_);
// printf("thread_count in for = [%d]\n",thread_count_now);
if(thread_count_now < MAX_THREADS)
{
printf("CREATE thread [%d]\n",i);
struct thread_struct struct1;
struct1.arg1 = i;
struct1.arg2 = 999;
pthread_t temp_thread;
rc = pthread_create(&temp_thread, NULL, &thread_test, (void *)&struct1);
if (rc)
{
printf("Unable to create thread %d\n",rc);
sleep(1);
pthread_detach(temp_thread);
goto create_thread;
}
}
else
{
printf("Thread POOL full %d of %d\n",thread_count_now,MAX_THREADS);
sleep(1);
goto create_thread;
}
}
pthread_attr_destroy(&attrs);
pthread_mutex_destroy(&mutex_);
// pthread_attr_destroy(&attrs);
printf("Proccess completed!\n");
pthread_exit(NULL);
return 1;
}
After spawning 300 threads it begins to give
errors, return code from pthread_create() is 11, and after that keeps executing them one by one.
What im i doing wrong?
According to this website, error code 11 corresponds to EAGAIN which means according to this:
Insufficient resources to create another thread.
A system-imposed limit on the number of threads was encountered.
Hence to solve your problem either create less threads or wait for running ones to finish before creating new ones.
You can also change default thread stack size see pthread_attr_setstacksize

Parallel merge sort useing _beginthreadex windows API in C++

I'm trying to implement merge sort using win32 _beginthreadex multiple threads in c++. basically it uses _beginthreadex instead of function call to make recursion in each thread. so it will has as many threads as possible. the while loop after the two _beginthreadex call is to check if the children threads finish there job. But when the program access the array a and b, it gives an error that unable to read the memory, I can't find what the problem is. It seems that in the sorting section in children threads the program try to access invalid memory address that info->b goes to the address 0xcccccccc {???}
Thank you
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <process.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <sstream>
#include <array>
#include <stdio.h>
using namespace std;
struct ThreadInfo
{
int* a;
int* b;
int low;
int high;
bool run;
};
unsigned __stdcall mergesort(void* x) {
ThreadInfo* info = (ThreadInfo*)x;
if ((info->low) < (info->high))
{
int pivot = ((info->low)+(info->high))/2;
ThreadInfo lowInfo;
ThreadInfo highInfo;
lowInfo.a=info->a;
lowInfo.low=info->low;
lowInfo.high=pivot;
lowInfo.run=true;
highInfo.b=info->b;
highInfo.low=pivot+1;
highInfo.high=info->high;
highInfo.run=true;
//HANDLE myhandlerUp, myhandlerDown;
//creat sub-thread
_beginthreadex(NULL, 0, mergesort, &lowInfo, 0, 0);
//WaitForSingleObject(myhandlerUp,INFINITE);
_beginthreadex(NULL, 0, mergesort, &highInfo, 0, 0);
//WaitForSingleObject(myhandlerDown,INFINITE);
//check if any child threads are working
bool anyRun = true;
while (anyRun)
{
anyRun = false;
anyRun = lowInfo.run || highInfo.run;
}
//doing merge sort
int h,i,j,k,low, high;
low = info->low;
high = info->high;
h=low;
i=low;
j=pivot+1;
while((h<=pivot)&&(j<=high))
{
if(info->a[h]<=info->a[j])
{
info->b[i]=info->a[h];
h++;
}
else
{
info->b[i]=info->a[j];
j++;
}
i++;
}
if(h>pivot)
{
for(k=j; k<=high; k++)
{
info->b[i]=info->a[k];
i++;
}
}
else
{
for(k=h; k<=pivot; k++)
{
info->b[i]=info->a[k];
i++;
}
}
for(k=low; k<=high; k++) info->a[k]=info->b[k];
}
info->run = false;
return 0;
}
void main()
{
ThreadInfo info;
int inputArr[12] = {12,10,43,23,-78,45,123,56,98,41,90,24};
int copiedArr[12]={0,0,0,0,0,0,0,0,0,0,0,0};
info.a=inputArr;
info.b=copiedArr;
for(int i=0; i<12; i++)
cout<<info.a[i]<<" ";
cout<<endl;
info.low=0;
info.high=(11);
info.run=true;
_beginthreadex(NULL, 0, mergesort, &info, 0, 0);
bool finish = info.run;
while(finish){
cout<<"Running...."<<endl;
Sleep(1000);
}
cout<<"After run the result is "<<endl;
for(int i=0; i<12; i++)
cout<<inputArr[i]<<" ";
cout<<endl;
getchar();
}

Why aren't my threads running?

// windows_procon.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <process.h>
using namespace std;
HANDLE mutex;
HANDLE emptySlots;
HANDLE filledSlots;
#define BUFFER_SIZE 10
void *producer(void *);
void *consumer(void *);
int produceItem(void);
void printBuffer(void);
int buffer[BUFFER_SIZE];
int head = 0;
int tail = 0;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD prodThrdID, consThrdID;
mutex = CreateMutex(NULL,FALSE,NULL);
emptySlots = CreateSemaphore(NULL,BUFFER_SIZE,BUFFER_SIZE,NULL);
filledSlots = CreateSemaphore(NULL,0,0,NULL);
srand(time(NULL));
_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))producer,
0, 0, (unsigned int *)&prodThrdID);
_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))consumer,
0, 0, (unsigned int *)&consThrdID);
return 0;
}
void *producer(void *n)
{
int item;
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(emptySlots,INFINITE);
WaitForSingleObject(mutex,INFINITE);
item = produceItem();
//printf("Producing");
cout << "Producing: " << item << endl;
//logfile << "Producing: "<< item << endl;
//fprintf(logfile, "Producing: %d \n", item);
buffer[head] = item;
head = (head + 1) % BUFFER_SIZE;
printBuffer();
ReleaseMutex(mutex);
ReleaseSemaphore(filledSlots,1, NULL);
}
return n;
}
void *consumer(void *n)
{
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(filledSlots,INFINITE);
//Sleep(500);
WaitForSingleObject(mutex,INFINITE);
cout << "Consuming: " << buffer[tail] << endl;
buffer[tail] = 0;
tail = (tail + 1) % BUFFER_SIZE;
printBuffer();
ReleaseMutex(mutex);
ReleaseSemaphore(emptySlots,1, NULL);
}
return n;
}
int produceItem(void)
{
int x = (rand()%11 + 1);
return x;
}
void printBuffer(void)
{
for(int i = 0; i <BUFFER_SIZE; i++)
{
printf("%d ", buffer[i]);
}
printf("END \n");
}
My program here is supposed to be an algorithm for the producer-consumer problem. I think I have the algorithm correct my only problem is that I'm having trouble getting the threads to run properly. Can someone tell me what the issue is?
You need to wait for the threads you create with _beginthreadex to do their work, as it stands you program will exit immediately after creating them. I haven't looked any further at you logic.
Here is an example.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
WaitForSingleObject( hThread, INFINITE );