Reputation: 165
What I want to accomplish:
In the main function are created two threads. They increment a global variable with the number 5. And send a signal to consumer thread that decrements the variables.In the consumer thread between each decrementation the current value is displayed. The main thread has to wait until all the threads are finished and then exit.
What I get:
Some times the main function exits before the consumer had a chance to display the results. I'm using pthread_join, but it returns error code 3.
Any Ideas how to get the wanted results?
The code is bellow.
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
static pthread_mutex_t mtx;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *producer(void *arg);
void *consumer(void *arg);
static int avail = 0;
int main(int argc, char *argv[]){
pthread_t cons1, prod1, prod2;
int status;
int t1;
int t2;
int t3;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutexattr_t mtxAttr;
pthread_mutexattr_settype(&mtxAttr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&mtx, &mtxAttr);
t1 = pthread_create(&prod1, &attr, producer, NULL);
if(t1 != 0){
perror("problem1");
}
t2 = pthread_create(&prod2, &attr, producer, NULL);
if(t2 != 0){
perror("problem2");
}
t3 = pthread_create(&cons1, &attr, consumer, NULL);
if(t3 != 0){
perror("problem3");
}
status = pthread_join(t1, NULL);
if(status != 0){
perror("can't join1");
}
status = pthread_join(t2, NULL);
if(status != 0){
perror("can't join2");
printf("\n%d\n", status);
}
status = pthread_join(t3, NULL);
if(status != 0){
printf("%s",strerror(errno));
}
printf("\nend result \t%d\n",avail);
printf("fin\n");
//while(1){}
return 0;
}
void *producer(void *arg){
int s;
printf("producer\n");
s = pthread_mutex_lock(&mtx);
avail+=5;
s = pthread_mutex_unlock(&mtx);
s = pthread_cond_signal(&cond);
pthread_exit(NULL);
}
void *consumer(void *arg){
int s;
while(1) {
s = pthread_mutex_lock(&mtx);
if(s !=0 ){
perror("lock err");
}
while (avail == 0) {
s = pthread_cond_wait(&cond, &mtx);
}
while (avail > 0) {
avail--;
printf("Temp: %d \n",avail);
}
s = pthread_mutex_unlock(&mtx);
}
printf("done");
pthread_exit(NULL);
}
Upvotes: 0
Views: 3973
Reputation: 5493
Don't join on t1
, t2
or t3
. Those are the return codes of the pthread_create()
function. Use pthread_join()
on prod1
, prod2
and cons1
instead. And please compile with -Wall -Wextra
.
Upvotes: 4