How to avoid global semaphores and queues when using threads - c++

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);
}

Related

Multiple Definitions Error of Global Arrays [duplicate]

This question already has answers here:
c++ multiple definitions of a variable
(5 answers)
multiple definition error c++
(2 answers)
What exactly is One Definition Rule in C++?
(1 answer)
Closed 2 years ago.
I am attempting to compile my c++ code, and I continue getting the error:
/tmp/ccEsZppG.o:(.bss+0x0): multiple definition of `mailboxes'
/tmp/ccEZq43v.o:(.bss+0x0): first defined here
/tmp/ccEsZppG.o:(.bss+0xc0): multiple definition of `threads'
/tmp/ccEZq43v.o:(.bss+0xc0): first defined here
/tmp/ccEsZppG.o:(.bss+0x120): multiple definition of `semaphores'
/tmp/ccEZq43v.o:(.bss+0x120): first defined here
collect2: error: ld returned 1 exit status
Here is my code:
addem.cpp
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include "mailbox.h"
using namespace std;
void *sumUp(void *arg);
int main(int argc, char *argv[]) {
int numThreads, minThreads, maxInt, minInt;
if (argc < 3) {
cout << "Error: Need three arguments" << endl;
return 1;
}
numThreads = atoi(argv[1]);
maxInt = atoi(argv[2]);
minThreads = 1;
minInt = 1;
if (numThreads < 1) {
cout << "Cannot work with less than one thread\n"
<< "It's okay but do better next time!\n"
<< "We'll work with 1 thread this time.\n";
numThreads = minThreads;
} else if (numThreads > MAXTHREAD) {
cout << "Sorry, the max for threads is 10.\n"
<< "We'll work with 10 threads this time.\n";
numThreads = MAXTHREAD;
}
if (maxInt < 1) {
cout << "What do you want me to do? I can't count backwards!\n"
<< "I can barely count forwards! Let's make the max number\n"
<< "be 1 to save time\n";
maxInt = minInt;
}
struct msg outgoingMail[numThreads];
int divider = maxInt / numThreads;
int count = 1;
//initialize arrays (mailboxes, semaphores)
for (int i = 0; i < numThreads; i++) {
sem_init(&semaphores[i], 0, 1);
outgoingMail[i].iSender = 0;
outgoingMail[i].type = RANGE;
outgoingMail[i].value1 = count;
count = count + divider;
if (i = numThreads - 1) {
outgoingMail[i].value2 = maxInt;
} else {
outgoingMail[i].value2 = count;
}
}
for (int message = 0; message < numThreads; message++) {
SendMsg(message+1, outgoingMail[message]);
}
int thread;
for (thread = 0; thread <= numThreads; thread++) {
pthread_create(&threads[thread], NULL, &sumUp, (void *)(intptr_t)(thread+1));
}
struct msg incomingMsg;
int total = 0;
for (thread = 0; thread < numThreads; thread++) {
RecvMsg(0, incomingMsg);
total = total + incomingMsg.value1;
}
cout << "The total for 1 to " << maxInt << " using "
<< numThreads << " threads is " << total << endl;
return 0;
}
void *sumUp(void *arg) {
int index,total;
index = (intptr_t)arg;
struct msg message;
RecvMsg(index, message);
message.iSender = index;
message.type = ALLDONE;
total = 0;
for (int i = message.value1; i <= message.value2; i++) {
total += i;
}
SendMsg(0, message);
return (void *) 0;
}
mailbox.cpp
#include <stdio.h>
#include <iostream>
#include "mailbox.h"
using namespace std;
int SendMsg(int iTo, struct msg &Msg) {
if (safeToCall(iTo)) {
cout << "Error calling SendMsg" << endl;
return 1;
}
sem_wait(&semaphores[iTo]);
mailboxes[iTo] = Msg;
sem_post(&semaphores[iTo]);
return 0;
}
int RecvMsg(int iFrom, struct msg &Msg) {
sem_wait(&semaphores[iFrom]);
if (safeToCall(iFrom)) {
cout << "Error calling RecvMsg" << endl;
return 1;
}
mailboxes[iFrom] = Msg;
sem_post(&semaphores[iFrom]);
return 0;
}
bool safeToCall(int location) {
bool safe = !(location < 0 || location > MAXTHREAD + 1);
return safe;
//return true;
}
mailbox.h
#ifndef MAILBOX_H_
#define MAILBOX_H_
#define RANGE 1
#define ALLDONE 2
#define MAXTHREAD 10
#include <semaphore.h>
#include <pthread.h>
struct msg {
int iSender; /* sender of the message (0 .. numThreads)*/
int type; /* its type */
int value1; /* first value */
int value2; /* second value */
};
struct msg mailboxes[MAXTHREAD + 1];
pthread_t threads[MAXTHREAD + 1];
sem_t semaphores[MAXTHREAD + 1];
int SendMsg(int iTo, struct msg &Msg);
int RecvMsg(int iFrom, struct msg &Msg);
bool safeToCall(int location);
#endif
I am compiling the code with the command
g++ -o addem addem.cpp mailbox.cpp -lpthread
I have tried commenting out all of the function bodies in the source code to leave them as stub functions, and the same error occurs. The only way I have been able to compile the file is if I comment out the function bodies, and remove
#include "mailbox.h"
From at least one of the files. I feel it has to do with how I am initializing the arrays? But I cannot figure out a workaround.

Pthread segment fault using pointer to variable in main

I'm new to pthread and attempting to implement a producer/consumer problem that will let the user pick buffer size, # of producers, # of consumers, and total # of items. I've been looking through what I thought were similar things on stack overflow, but can't seem to get it right.
My code has a main class and it spawns producers and consumers. It hands the producers and consumers a pointer to a stack initialized in main (or at least I'm trying to). I thought that what I was doing was legal and in CLion I get the predictive text options I want so I thought I linked it properly but I'm segfaulting when I try to read the top element.
I used GDB to make sure I knew what line I was crashing on, but don't understand what's wrong with my setup. While debugging I confirmed that a producer goes through its push() command first, but the consumer fails when attempting top() or pop(). I'd seen some threads here where the OP had problems because they didn't join their threads, but I am so I'm a little lost.
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stack>
#include <cstring>
#include <semaphore.h>
#include <pthread.h>
#define N 10000
sem_t mutex;
sem_t fullCount;
sem_t emptyCount;
int iCount = 0;
typedef struct _thread_data{
int id;
int itemcount;
std::stack<char>* ptr;
}thread_data;
void *producer(void *arg){
std::cout << "spawned producer\n";
thread_data *data = (thread_data *)arg;
while(true){
char message = 'X';
sem_wait(&emptyCount);
sem_wait(&mutex);
if(iCount < data->itemcount){
data->ptr->push(message);
iCount++;
char temp [25];
sprintf(temp, "p:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size());
std::cout << temp;
//std::cout << "hi I'm a producer\n";
sem_post(&mutex);
sem_post(&fullCount);
}
else{
sem_post(&fullCount);
sem_post(&mutex);
pthread_exit(nullptr);
}
}
}
void *consumer(void *arg){
std::cout << ("spawned consumer\n");
thread_data *data = (thread_data *)arg;
while(true){
char message;
sem_wait(&fullCount);
sem_wait(&mutex);
if(iCount < data->itemcount) {
message = data->ptr->top(); //SEGFAULT
char temp[25];
printf(temp, "c:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size());
data->ptr->pop();
std::cout << temp;
//std::cout << "Hi I'm a consumer\n";
sem_post(&mutex);
sem_post(&emptyCount);
}
else if (iCount == data->itemcount){
message = data->ptr->top(); //SEGFAULT
char temp[25];
printf(temp, "c:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size());
data->ptr->pop();
std::cout << temp;
sem_post(&emptyCount);
sem_post(&mutex);
pthread_exit(nullptr);
}
else{
sem_post(&mutex);
pthread_exit(nullptr);
}
}
}
int main(int argc, char *argv[]){
int bufferSize = N;
int pThreadCount,cThreadCount,itemCount;
for (int x = 0; x < argc; ++x) {
if(strcmp(argv[x],"-b") == 0){
bufferSize = atoi(argv[x+1]);
}
if(strcmp(argv[x],"-p") == 0){
pThreadCount = atoi(argv[x+1]);
}
if(strcmp(argv[x],"-c") == 0){
cThreadCount = atoi(argv[x+1]);
}
if(strcmp(argv[x],"-i") == 0){
itemCount = atoi(argv[x+1]);
}
}
sem_init(&mutex,1,1);
sem_init(&fullCount,1,0);
sem_init(&emptyCount,1,bufferSize);
std::stack<char> myStack;
pthread_t myPThreads[pThreadCount];
thread_data thrData[pThreadCount];
pthread_t myCThreads[cThreadCount];
thread_data cThrData[cThreadCount];
for (int i = 0; i < pThreadCount; ++i) {
thrData[i].id = i;
thrData[i].itemcount = itemCount;
thrData[i].ptr = &myStack;
pthread_create(&myPThreads[i], NULL, producer, &thrData[i]);
}
for (int i = 0; i < cThreadCount; ++i) {
cThrData[i].id = i;
cThrData[i].itemcount = itemCount;
thrData[i].ptr = &myStack;
pthread_create(&myCThreads[i], NULL, consumer, &cThrData[i]);
}
for (int k = 0; k < pThreadCount; ++k) {
pthread_join(myPThreads[k], NULL);
}
for (int j = 0; j < cThreadCount; ++j) {
pthread_join(myCThreads[j], NULL);
}
return 0;
}
iCount <= data->itemcount is always true. consumer never exits the loop. At some point, it exhausts the stack, and the subsequent top() call exhibits undefined behavior.
cThrData[i].ptr is never initialized, for any i. consumer calls top() through an uninitialized pointer, whereupon the program exhibits undefined behavior.

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 );

Producer-Consumer Issue

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;
....