I am experimenting with pthreads. I am trying to create three threads and have them operate on a global char buffer. I am using mutex lock and unlock for their critical sections. The program flow should go: Main spawns three threads. Thread one locks, initializes the buffer, prints it out, signals thread two, and unlocks. Thread two enters its critical section operates on the buffer and signals thread three, etc. It seems to work, sometimes. Other times, it seems like it is getting suck in a spin lock. Any help in the right direction would be great. Thanks.
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
using namespace std;
const int num_threads = 3;
char buffer[100];
pthread_mutex_t buffer_mutex = pthread_mutex_initializer;
pthread_cond_t buffer_cond = pthread_cond_initializer;
void* firstthreadfunc(void* proc) {
string a = "data received";
pthread_mutex_lock(&buffer_mutex);
sleep(1);
cout<<"threadone"<<endl;
for(int i = 0;i<14;i++){
buffer[i] = a[i];
cout<<buffer[i];
}
cout<<endl;
pthread_cond_signal(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return null;
}
void* secondthreadfunc(void* proc) {
string a = "data processed";
pthread_mutex_lock(&buffer_mutex);
pthread_cond_wait(&buffer_cond, &buffer_mutex);
sleep(1);
cout<<"threadtwo"<<endl;
for(int i = 0; i<15 ;i++){
buffer[i] = a[i];
cout<<buffer[i];
}
cout<<endl;
pthread_cond_signal(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return null;
}
void* thirdthreadfunc(void* proc) {
string a = "data sent";
pthread_mutex_lock(&buffer_mutex);
pthread_cond_wait(&buffer_cond, &buffer_mutex);
sleep(1);
cout<<"thread three"<<endl;
for(int i = 0;i<9;i++){
buffer[i] = a[i];
cout<<buffer[i];
}
cout<<endl;
pthread_cond_signal(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return null;
}
int main() {
pthread_t p_threadone, p_threadtwo, p_threadthree;;
pthread_attr_t attr;
pthread_attr_init(&attr);
for(int i = 0;i<100;i++){
buffer[i] = 'a';
}
//create threads
cout<<"creating threads"<<endl;
pthread_create(&p_threadone, &attr, firstthreadfunc, null);
pthread_create(&p_threadtwo, &attr, secondthreadfunc, null);
pthread_create(&p_threadthree, &attr, thirdthreadfunc, null);
//terminate threads
pthread_join(p_threadone,null);
pthread_join(p_threadtwo,null);
pthread_join(p_threadthree,null);
return 0;
}
Thanks WhozCraig and Tony, your answers resolved the issue. I understand what I was doing wrong.
First, where you're stuck. The following line in either thread2 or thread3 is the sticking point:
pthread_cond_wait(&buffer_cond, &buffer_mutex);
And by now you're asking, "Why?" Because your mistaking a condition variable as a state; not a signaling mechanism. Condition variables are intended to be used to signal interested waiters of change in state of something else: the predicate. You have none. Consider the following modified version of your code.
This uses two predicate values (I advise you stick with one per condvar until you become more comfortable with them; start simple), protecting them with the same mutex and signaling their change with the same condition variable. The important thing to note is that we don't wait on the condition variable until we know the predicate we're waiting for is not ready yet. And since we have the mutex locked, we can safely do check that predicate:
#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;
const int NUM_THREADS = 3;
char buffer[100];
bool bDataReady = false;
bool bDataWaiting = false;
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buffer_cond = PTHREAD_COND_INITIALIZER;
void* firstThreadFunc(void* proc)
{
string a = "Data Received";
pthread_mutex_lock(&buffer_mutex);
cout<<"ThreadOne"<<endl;
std::copy(a.begin(), a.end(), buffer);
buffer[a.size()] = 0;
cout << buffer << endl;
bDataReady = true;
pthread_cond_broadcast(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return NULL;
}
void* secondThreadFunc(void* proc)
{
string a = "Data Processed";
pthread_mutex_lock(&buffer_mutex);
while (!bDataReady)
pthread_cond_wait(&buffer_cond, &buffer_mutex);
cout<<"ThreadTwo"<<endl;
std::copy(a.begin(), a.end(), buffer);
buffer[a.size()] = 0;
cout << buffer << endl;
bDataReady = false;
bDataWaiting = true;
pthread_cond_broadcast(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return NULL;
}
void* thirdThreadFunc(void* proc)
{
string a = "Data Sent";
pthread_mutex_lock(&buffer_mutex);
while (!bDataWaiting)
pthread_cond_wait(&buffer_cond, &buffer_mutex);
cout<<"Thread Three"<<endl;
std::copy(a.begin(), a.end(), buffer);
buffer[a.size()] = 0;
cout << buffer << endl;
bDataWaiting = false;
pthread_cond_broadcast(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
return NULL;
}
int main() {
pthread_t p_threadOne, p_threadTwo, p_threadThree;;
pthread_attr_t attr;
pthread_attr_init(&attr);
for(int i = 0;i<100;i++){
buffer[i] = 'a';
}
//create Threads
cout<<"creating threads"<<endl;
pthread_create(&p_threadOne, &attr, firstThreadFunc, NULL);
pthread_create(&p_threadTwo, &attr, secondThreadFunc, NULL);
pthread_create(&p_threadThree, &attr, thirdThreadFunc, NULL);
//terminate Threads
pthread_join(p_threadOne,NULL);
pthread_join(p_threadTwo,NULL);
pthread_join(p_threadThree,NULL);
return 0;
}
Output
creating threads
ThreadOne
Data Received
ThreadTwo
Data Processed
Thread Three
Data Sent
Related
I have the following program that should take in "orders" and process them synchronously. I think most of it works, however critical region 4 doesn't get the mutex until after all of the orders are placed. Where should the cond_vars be placed so that region 4 gets the lock while orders are still being produced?
#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <cstdlib>
using namespace std;
#define MAX 10
#define N 4
// Data structure to represent a simplified Order
// that has an order number and an item number.
struct Order
{
int order_num;
int item_num;
};
Order new_orders [N]; // array of elements of type Order to be used as
a shared buffer
int num_new_orders = 0; // count of number of new (i.e., unprocessed)
orders
int order_num = 0; // global variable used to generate unique order
numbers
pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t console_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t spaceAvailabe = PTHREAD_COND_INITIALIZER;
pthread_cond_t newOrder = PTHREAD_COND_INITIALIZER;
pthread_cond_t consoleVar = PTHREAD_COND_INITIALIZER;
void* takeOrders(void* arg)
{
int item;
int index = 0;
for(int i = 0; i < MAX; ++i) {
// Beginning of critical region 1
pthread_mutex_lock(&console_mutex);
// Get user input
cout << "Enter a menu item number between 1 and 50: ";
cin >> item;
// Print new order's details
cout << "Got new order! Order number is " << order_num <<
" and item number: " << item << std::endl;
// End of critical region 1
pthread_mutex_unlock(&console_mutex);
// Beginning of critical region 2
pthread_mutex_lock(&data_mutex);
// Put new order into new orders buffer and update number of new orders
while(num_new_orders>=MAX){
pthread_cond_wait(&spaceAvailabe, &console_mutex);
}
new_orders[index].order_num = order_num;
new_orders[index++].item_num = item;
++num_new_orders;
pthread_cond_signal(&newOrder);
// End of critical region 2
pthread_mutex_unlock(&data_mutex);
// Update order number so that next order gets a different number
++order_num;
// If the end of the new orders buffer is reached, wrap back around
if(index == N)
index = 0;
}
pthread_exit(NULL);
}
void* processOrders(void* arg)
{
int item;
int index = 0;
int o_num;
for(int i = 0; i < MAX; ++i) {
// Beginning of critical region 3
pthread_mutex_lock(&data_mutex);
// Retrieve new order details from buffer and update number of new orders
while(num_new_orders==0)
{
pthread_cond_wait(&newOrder, &data_mutex);
}
o_num = new_orders[index].order_num;
item = new_orders[index++].item_num;
--num_new_orders;
pthread_cond_signal(&spaceAvailabe);
// End of critical region 3
pthread_mutex_unlock(&data_mutex);
// Beginning of critical region 4
pthread_mutex_lock(&console_mutex);
// Print retrieved order's details
cout << "Processing order number " << o_num << " with item number: " <<
item << std::endl;
// End of critical region 4
pthread_mutex_unlock(&console_mutex);
// Suspend self for 1 second
sleep(1);
// If the end of the new orders buffer is reached, wrap back around
if(index == N)
index = 0;
}
pthread_exit(NULL);
}
int main()
{
// Create threads to take and process orders
pthread_t id1, id2;
pthread_create(&id1, NULL, processOrders, NULL);
pthread_create(&id2, NULL, takeOrders, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
// Print goodbye message
cout << "Phew! Done with orders for today!" << endl;
pthread_exit(NULL);
}
I have written a program couple of months back How to execute thread in sync order. I am posting the same program here. Which might help you. Also do not mix C++ code with C. Better use stdio.h instead of iostream. In C++ 11 implementation of thread is much easier than C.
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock3 = PTHREAD_MUTEX_INITIALIZER;
int TRUE = 1;
void print(char *p)
{
printf("%s",p);
}
void * threadMethod1(void *arg)
{
printf("In thread1\n");
do{
pthread_mutex_lock(&lock1);
pthread_cond_wait(&cond1, &lock1);
print("I am thread 1st\n");
pthread_cond_signal(&cond3);/* Now allow 3rd thread to process */
pthread_mutex_unlock(&lock1);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod2(void *arg)
{
printf("In thread2\n");
do
{
pthread_mutex_lock(&lock2);
pthread_cond_wait(&cond2, &lock2);
print("I am thread 2nd\n");
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock2);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod3(void *arg)
{
printf("In thread3\n");
do
{
pthread_mutex_lock(&lock3);
pthread_cond_wait(&cond3, &lock3);
print("I am thread 3rd\n");
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&lock3);
}while(TRUE);
pthread_exit(NULL);
}
int main(void)
{
pthread_t tid1, tid2, tid3;
int i = 0;
printf("Before creating the threads\n");
if( pthread_create(&tid1, NULL, threadMethod1, NULL) != 0 )
printf("Failed to create thread1\n");
if( pthread_create(&tid2, NULL, threadMethod2, NULL) != 0 )
printf("Failed to create thread2\n");
if( pthread_create(&tid3, NULL, threadMethod3, NULL) != 0 )
printf("Failed to create thread3\n");
pthread_cond_signal(&cond1);/* Now allow first thread to process first */
/*
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);*/
sleep(1);
TRUE = 0;/* Stop all the thread */
sleep(3);
exit(0);
}
I have the test code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t th_worker, th_worker2;
void * worker2(void *data) {
for(int i = 0; i< 1000000; i++){
printf("thread for worker2----%d\n", i);
usleep(500);
}
}
void * worker(void *data){
pthread_create(&th_worker2, NULL, worker2, data);
for(int i = 0; i< 100; i++){
printf("thread for worker-----%d\n", i);
usleep(500);
}
}
void join(pthread_t _th){
pthread_join(_th, NULL);
}
In main() function, If I call join(the_worker2):
int main() {
char* str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void*) str);
/* problem in here */
join(th_worker2);
return 1;
}
--> Segment Fault error
Else, i call:
join(the_worker);
join(th_worker2);
---> OK
Why have segment fault error in above case?
Thanks for help !!!
If you posted all your code, you have a race condition.
main is synchronized with the start of worker but not worker2.
That is, main is trying to join th_worker2 before worker has had a chance to invoke pthread_create and set up th_worker2 with a valid [non-null] value.
So, th_worker2 will be invalid until the second pthread_create completes, but that's already too late for main. It has already fetched th_worker2, which has a NULL value and main will segfault.
When you add the join for th_worker, it works because it guarantees synchronization and no race condition.
To achieve this guarantee without the join, have main do:
int
main()
{
char *str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void *) str);
// give worker enough time to properly start worker2
while (! th_worker2)
usleep(100);
/* problem in here */
join(th_worker2);
return 1;
}
An even better way to do this is to add an extra variable. With this, the first loop is not needed [but I've left it in]:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int worker_running;
pthread_t th_worker;
int worker2_running;
pthread_t th_worker2;
void *
worker2(void *data)
{
// tell main we're fully functional
worker2_running = 1;
for (int i = 0; i < 1000000; i++) {
printf("thread for worker2----%d\n", i);
usleep(500);
}
return NULL;
}
void *
worker(void *data)
{
// tell main we're fully functional
worker_running = 1;
pthread_create(&th_worker2, NULL, worker2, data);
for (int i = 0; i < 100; i++) {
printf("thread for worker-----%d\n", i);
usleep(500);
}
return NULL;
}
void
join(pthread_t _th)
{
pthread_join(_th, NULL);
}
int
main()
{
char *str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void *) str);
// give worker enough time to properly start worker2
// NOTE: this not necessarily needed as loop below is better
while (! th_worker2)
usleep(100);
// give worker2 enough time to completely start
while (! worker2_running)
usleep(100);
/* problem in here (not anymore!) */
join(th_worker2);
return 1;
}
I'm new to threads and seem to be having a timing problem. When I run my code my output is...
Data received!
Data processed!
and then it just hangs. I assume I'm using wait and signal incorrectly. Help would be greatly appreciated.
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
char buffer [100];
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buffer_cond = PTHREAD_COND_INITIALIZER;
void* threadFunc(void *proc){
if((int)proc == 0){
pthread_mutex_lock(&buffer_mutex);
sprintf(buffer, "Data received!\n");
printf("%s", buffer);
pthread_cond_signal(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
}
else if((int)proc == 1){
pthread_mutex_lock(&buffer_mutex);
pthread_cond_wait(&buffer_cond, &buffer_mutex);
sprintf(buffer, "Data processed!\n");
printf("%s", buffer);
pthread_cond_signal(&buffer_cond);
pthread_mutex_unlock(&buffer_mutex);
}
else{
sleep(1);
pthread_mutex_lock(&buffer_mutex);
pthread_cond_wait(&buffer_cond, &buffer_mutex);
sprintf(buffer, "Data sent!\n");
printf("%s", buffer);
pthread_mutex_unlock(&buffer_mutex);
}
return(NULL);
}
int main()
{
pthread_t threads[3];
for(int i = 0; i < 3; i++){
pthread_create(&threads[i], NULL, threadFunc, (void *) i);
}
for(int i = 0; i < 3; i++){
pthread_join(threads[i], NULL);
}
return 0;
}
A condition variable is near-useless without a predicate, a conditional state that dictates what has changed. The condition variable is little more than a signaling mechanism to announce that "something" may have changed, but you still need to manage the "what". And that mutex is what protects that "what".
For example:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <pthread.h>
char buffer [100];
int state = 0;
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buffer_cond = PTHREAD_COND_INITIALIZER;
void* threadFunc(void *proc)
{
intptr_t iptr = (intptr_t)proc;
pthread_mutex_lock(&buffer_mutex);
switch(iptr)
{
case 0:
{
while (state != 1) // 1 means data available
pthread_cond_wait(&buffer_cond, &buffer_mutex);
// mutex is locked. access predicate data
printf("Data received: %s\n", buffer);
state = 2; // advance state
pthread_mutex_unlock(&buffer_mutex);
pthread_cond_broadcast(&buffer_cond);
}
break;
case 1:
{
while (state != 2)
pthread_cond_wait(&buffer_cond, &buffer_mutex);
// mutex is locked. access predicate data
printf("Data processed: %s\n", buffer);
pthread_mutex_unlock(&buffer_mutex);
}
break;
default:
{
// setup initial send-state
printf("Data sent: %s\n", buffer);
state = 1;
pthread_mutex_unlock(&buffer_mutex);
pthread_cond_broadcast(&buffer_cond);
}
}
return NULL;
}
int main()
{
pthread_t threads[3];
intptr_t i = 0;
strcpy(buffer, "Some message");
for(i = 0; i < 3; i++){
pthread_create(&threads[i], NULL, threadFunc, (void *) i);
}
for( i = 0; i < 3; i++)
pthread_join(threads[i], NULL);
return 0;
}
Output
Data sent: Some message
Data received: Some message
Data processed: Some message
This simply starts up three threads. One (id=0) will wait for the state to become 1, then proceed with its job of announcing what happened, advancing the state, and signaling the condition. The second (id=1) waits for that state, does its job similarly, then simply exits as there is nothing else to to. The third (id=2) is the one that kicks off the process, then silently finishes.
Note that at no time is the predicate data (the state) changed or checked without being under the protection of the mutex on whatever thread is doing said check/changing.
Three timelines with mutex-latch state and which thread owns it will speak volumes in understanding how this works, and I highly advise you get a pencil and paper to assist on that regard.
Best of luck.
I am attempting to learn about semaphores and multi-threading. The example I am working with creates 1 to t threads with each thread pointing to the next and the last thread pointing to the first thread. This program allows each thread to sequentially take a turn until all threads have taken n turns. That is when the program ends. The only problem is in the tFunc function, I am busy waiting until it is a specific thread's turn. I want to know how to use semaphores in order to make all the threads go to sleep and waking up a thread only when it is its turn to execute to improve efficiency.
int turn = 1;
int counter = 0;
int t, n;
struct tData {
int me;
int next;
};
void *tFunc(void *arg) {
struct tData *data;
data = (struct tData *) arg;
for (int i = 0; i < n; i++) {
while (turn != data->me) {
}
counter++;
turn = data->next;
}
}
int main (int argc, char *argv[]) {
t = atoi(argv[1]);
n = atoi(argv[2]);
struct tData td[t];
pthread_t threads[t];
int rc;
for (int i = 1; i <= t; i++) {
if (i == t) {
td[i].me = i;
td[i].next = 1;
}
else {
td[i].me = i;
td[i].next = i + 1;
}
rc = pthread_create(&threads[i], NULL, tFunc, (void *)&td[i]);
if (rc) {
cout << "Error: Unable to create thread, " << rc << endl;
exit(-1);
}
}
for (int i = 1; i <= t; i++) {
pthread_join(threads[i], NULL);
}
pthread_exit(NULL);
}
Uses mutexes and condition variables. Here's a working example:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int turn = 1;
int counter = 0;
int t, n;
struct tData {
int me;
int next;
};
pthread_mutex_t mutex;
pthread_cond_t cond;
void *tFunc(void *arg)
{
struct tData *data;
data = (struct tData *) arg;
pthread_mutex_lock(&mutex);
for (int i = 0; i < n; i++)
{
while (turn != data->me)
pthread_cond_wait(&cond, &mutex);
counter++;
turn = data->next;
printf("%d goes (turn %d of %d), %d next\n", data->me, i+1, n, turn);
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&mutex);
}
int main (int argc, char *argv[]) {
t = atoi(argv[1]);
n = atoi(argv[2]);
struct tData td[t + 1];
pthread_t threads[t + 1];
int rc;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
for (int i = 1; i <= t; i++)
{
td[i].me = i;
if (i == t)
td[i].next = 1;
else
td[i].next = i + 1;
rc = pthread_create(&threads[i], NULL, tFunc, (void *)&td[i]);
if (rc)
{
printf("Error: Unable to create thread: %d\n", rc);
exit(-1);
}
}
void *ret;
for (int i = 1; i <= t; i++)
pthread_join(threads[i], &ret);
}
Use N+1 semaphores. On startup, thread i waits on semaphore i. When woken up it "takes a turnand signals semaphorei + 1`.
The main thread spawns the N, threads, signals semaphore 0 and waits on semaphore N.
Pseudo code:
sem s[N+1];
thread_proc (i):
repeat N:
wait (s [i])
do_work ()
signal (s [i+1])
main():
for i in 0 .. N:
spawn (thread_proc, i)
repeat N:
signal (s [0]);
wait (s [N]);
Have one semaphore per thread. Have each thread wait on its semaphore, retrying if sem_wait returns EINTR. Once it's done with its work, have it post to the next thread's semaphore. This avoids the "thundering herd" behaviour of David's solution by waking only one thread at a time.
Also notice that, since your semaphores will never have a value larger than one, you can use a pthread_mutex_t for this.
I'm asked to write a program that will have 2 threads and print 5 random integers such that the first thread will generate a number, the second will print it. Then the first will generate the 2nd number, the second thread will print it... etc. using a mutex.
My code now execute it for one cycle. How can I extend it to make threads excute the methods 5 times?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* generate (void*);
void* print (void*);
pthread_mutex_t m;
int number = 5;
int genNumber;
int main()
{
int i;
srandom(getpid());
pthread_t th[2];
pthread_mutex_init(&m,NULL);
pthread_create(&th[0],NULL,generate,NULL);
pthread_create(&th[1],NULL,print, NULL);
for (i = 0; i < 2; i++)
pthread_join(th[i], NULL);
pthread_mutex_destroy(&m);
return 0;
}
void* generate(void* arg)
{
pthread_mutex_lock(&m);
genNumber = random() % 9;
printf("Generated #1 \n");
pthread_mutex_unlock(&m);
}
void* print(void* arg)
{
pthread_mutex_lock(&m);
printf("The number is %d " , genNumber);
pthread_mutex_unlock(&m);
pthread_exit(NULL);
}
Use condition variables to synchronize the two threads. When a thread has completed its work, it signals to the other thread to wake up, and then it goes to sleep to wait for more work. So something like this:
// Pseudocode
pthread_cond_t c1, c2;
pthread_mutex_t mutex;
// Thread 1 (producer):
for(int i = 0; i < 5; i++)
{
lock(mutex);
genNumber = random() % 9;
signal(c2);
wait(c1, mutex);
unlock(mutex);
}
// Thread 2 (consumer):
for(int i = 0; i < 5; i++)
{
lock(mutex);
wait(c2, mutex);
print("The number is %d\n", genNumber);
signal(c1);
unlock(mutex);
}
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
static int *generate(void *);
static int *print(void *);
pthread_mutex_t m;
pthread_cond_t con;
int munmber=10;
int gennumber;
int main() {
srandom(getpid());
pthread_t th1,th2;
pthread_mutex_init(&m,NULL);
pthread_create(&th2,NULL,print,NULL);
sleep(1);
pthread_create(&th1,NULL,generate,NULL);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
pthread_mutex_destroy(&m);
}
static int *generate(void *arg) {
int i;
while(i<5) {
pthread_mutex_lock(&m);
gennumber=random()%8;
printf("NUMMBER GENERATED.... \n");
pthread_cond_signal(&cond);
i++;
pthread_mutex_unlock(&m);
sleep(2);
if(i==5)
exit(1);
}
return 0;
}
static int *print(void *arg) {
int i;
while('a') {
pthread_cond_wait(&cond,&m);
printf("GENERATED NUMBER is %d\n",gennumber);
i++;
pthread_mutex_unlock(&m);
}
return 0;
}
A mutex is not sufficient here. You will need a condition variable to make sure that the numbers are printed in the correct order. Some pseudocode:
//producer thread:
for(int i = 0; i < 5; i++)
{
number = random();
signal the other thread with pthread_cond_signal
wait for signal from the consumer
}
// consumer thread
for(int i = 0; i < 5; i++)
{
wait for signal with pthread_cond_wait
print number
signal the producer to produce another number
}
You can do it like this:
int* generated = null;
void generate() {
int i = 0;
while (i<5) {
pthread_mutex_lock(&m);
if (generated == null) {
generated = malloc(int);
*generated = random() % 9;
printf("Generated #1 \n");
++i;
}
pthread_mutex_unlock(&m);
}
pthread_exit(NULL);
}
void print() {
int i = 0;
while (i<5) {
pthread_mutex_lock(&m);
if (generated != null) {
printf("The number is %d " , generated);
free(generated);
generated=null;
}
pthread_mutex_unlock(&m);
}
pthread_exit(NULL);
}
Actually I did write it without a compiler so there can be some errors but the concept should work.