Thread syncronization to print 5 random numbers - c++

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.

Related

How to make 5 threads read and write array concurrently

I'm having an attempt at the famous producer-consumer problem in c++ and I have came up with an implementation like this...
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
void *consumeThread(void *i);
void *produceThread(void *i);
using std::cout;
using std::endl;
//Bucket size
#define Bucket_size 10
int buckets[Bucket_size];
pthread_mutex_t lock;
pthread_cond_t consume_now, produce_now;
time_t timer;
int o = 0;
int p = 0;
int main()
{
int i[5] = {1, 2, 3, 4, 5};
pthread_t consumer[5];
pthread_t producer[5];
pthread_mutex_init(&lock, nullptr);
pthread_cond_init(&consume_now, nullptr);
pthread_cond_init(&produce_now, nullptr);
timer = time(nullptr) + 10;
srand(time(nullptr));
for (int x = 0; x < 5; x++)
{
pthread_create(&producer[x], nullptr, &produceThread, &i[x]);
}
for (int x = 0; x < 5; x++)
{
pthread_create(&consumer[x], nullptr, &consumeThread, &i[x]);
}
pthread_cond_signal(&produce_now);
for (int x = 0; x < 5; x++)
{
pthread_join(producer[x], nullptr);
pthread_join(consumer[x], nullptr);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&consume_now);
pthread_cond_destroy(&produce_now);
return 0;
}
void *consumeThread(void *i)
{
bool quit = false;
while (!quit)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&consume_now, &lock);
printf("thread %d consuming element at array[%d] : the element is %d \n", *((int *)i), o, buckets[o]);
buckets[o] = 0;
p++;
printArray();
usleep(100000);
pthread_cond_signal(&produce_now);
pthread_mutex_unlock(&lock);
quit = time(nullptr) > timer;
}
return EXIT_SUCCESS;
}
void *produceThread(void *i)
{
int a = 0;
bool quit = false;
while (!quit)
{
o = p % 10;
buckets[o] = (rand() % 20) + 1;
printf("thread %d adding element in array[%d] : the element is %d \n", *((int *)i), o, buckets[o]);
a++;
printArray();
usleep(100000);
quit = time(nullptr) > timer;
}
return EXIT_SUCCESS;
}
currently this solution has 5 producer threads and 5 consumer threads, however it only lets 1 thread produce and 1 thread consume at a time, is there a way to make 5 of the producer and consumer threads work concurrently?
Example output from the program:
thread 1 adding element in array[0] : the element is 6
[6,0,0,0,0,0,0,0,0,0]
Your first problem is that you are treating condition variables as if they have memory. In your main(), you pthread_cond_signal(), but at that point, you have no idea if any of your threads are waiting upon that condition. Since condition variables do not have memory, your signal may well be lost.
Your second problem is that o is effectively protected by the condition; since each consumer uses it; and each producer modifies it, you can neither permit multiple producers or consumers to execute concurrently.
Your desired solution amounts to a queue which you inject o's into from the producers; and collect them in the consumers. That way, your concurrency is gated by your ability to produce o's.

Killing thread from another thread c++

I am new to multithreading and i need your help.
Consider the following code:
vector <int> vec;
int j = 0;
void Fill()
{
for (int i = 0; i < 500; i++)
{
Sleep(500);
vec.push_back(i);
}
}
void Proces()
{
int count = 0;
int n=-1;
while (true) {
Sleep(250);
if (!vec.empty())
{
if (n != vec.back()) {
n = vec.back();
cout << n;
count++;
}
}
if (count == 101)break;
}
}
void getinput()
{
while (true) {
int k=0;
cin >> k;
//if the user enters an integer i want to kill all the threads
}
}
int main()
{
thread t1(Fill);
thread t2(Proces);
thread t3(getinput);
t1.join();
t2.join();
t3.join();
cout << "From main()";
}
The point is that i want to kill t1(Fill) and t2(Proces) from t3(getinput).Is there and way to do it,and if there is could you please post and example.
A common way to make a thread exit is to have an (atomic) flag that the thread checks to see if it should exit. Then externally you set this flag and the thread will notice it and exit naturally.
Something like
#include <thread>
#include <atomic>
#include <iostream>
#include <chrono>
// Flag telling the thread to continue or exit
std::atomic<bool> exit_thread_flag{false};
void thread_function()
{
// Loop while flag if not set
while (!exit_thread_flag)
{
std::cout << "Hello from thread\n";
std::this_thread::sleep_for(std::chrono::seconds(1)); // Sleep for one second
}
}
int main()
{
std::thread t{thread_function}; // Create and start the thread
std::this_thread::sleep_for(std::chrono::seconds(5)); // Sleep for five seconds
exit_thread_flag = true; // Tell thread to exit
t.join(); // Wait for thread to exit
}
You have to define an exit condition and lock the container before accessing it. Of course you could build an own collection as wrapper around an existing using proper locking and thus making it thread-safe.
Here is an example of locking and an exit condition:
class Test
{
public:
Test()
: exitCondition(false)
{
work = std::thread([this]() { DoWork(); });
}
~Test()
{
if (work.joinable())
work.join();
}
void Add(int i)
{
mutex.lock();
things.push_back(i);
mutex.unlock();
}
void RequestStop(bool waitForExit = false)
{
exitCondition.exchange(true);
if (waitForExit)
work.join();
}
private:
void DoWork()
{
while (!exitCondition)
{
mutex.lock();
if (!things.empty())
{
for (auto itr = things.begin(); itr != things.end();)
itr = things.erase(itr);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
mutex.unlock();
}
}
private:
std::vector<int> things;
std::thread work;
std::atomic<bool> exitCondition;
std::mutex mutex;
};
int wmain(int, wchar_t**)
{
Test t;
t.Add(1);
t.Add(2);
t.Add(3);
t.RequestStop(true);
return 0;
}
std::atomic<bool> exit_flag{false};
...
void Fill() {
for (int i = 0; i < 500; i++) {
if (exit_flag) return;
...
}
}
void Proces() {
while (true) {
if (exit_flag) return;
...
}
}
void getinput() {
while (true) {
...
if ( /* the user enters an integer i want to kill all the threads */ )
exit_flag = true;
}
}

Call join child pthread in main function

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

Why am i getting infinite loop for only thread # 0 after all 5 threads run for multi threading C++ dining philosophers riddle

Now all 5 threads are running. However after 5 threads are run for the first time. Only first thread (thread # 0) runs infinitely blocking rest of the threads. I only see thread # 0 idle (waiting) and consuming (eating) and again entering into infinite loop other 4 threads do not get a chance after 1st round.
struct sem_t_ * sem[5];
struct sem_t_ * lock;
class Phil
{
public:
Phil()
{
isThinking = isEating = 0;
mId = 0;
}
//~Phil();
bool isThinking;
bool isEating;
int mId;
void setID(int id)
{
mId = id;
}
void think()
{
isThinking = 1;
isEating = 0;
cout<<"Thread "<<mId<<" is idle!.\n";
}
void eat()
{
isThinking = 0;
isEating = 1;
cout<<"Thread "<<mId<<" is consuming!.\n";
}
};
void pause()
{
Sleep(1000);
}
Phil* pArray = new Phil[5];
void* thread_Create(void*param)
{
int value = 0;
int* id = (int*)param;
for(;;)
{
cout<<"Thread Id = "<<*id<<" running.\n";
pArray[*id].think();
sem_wait(&lock);
int left = *id;
int right = (*id)+1;
if( right > 4) right = 0;
//cout<<"Left = "<<left<<" Right = "<<right<<endl;
sem_getvalue(&sem[left],&value) ;
//cout<<"Left Value = "<<value<<endl;
if( value != 1 )
{
sem_post(&lock);
continue;
}
if( value != 1 )
{
sem_post(&lock);
continue;
}
sem_wait(&sem[left]);
sem_wait(&sem[right]);
pArray[*id].eat();
sem_post(&sem[left]);
sem_post(&sem[right]);
sem_post(&lock);
pause();
}
return 0;
}
void main(void)
{
int i = 0;
for(i=0; i< 5;i++)
{
pArray[i].setID(i);
sem_init(&sem[i],0,1);
}
sem_init(&lock, 0, 5);
pthread_t threads[5];
for(i=0; i< 5;i++)
{
pthread_create(&threads[i],NULL,thread_Create, (void*)&i);
pause();
}
for(i=0; i< 5;i++)
{
pthread_join(threads[i], NULL); //Main thread will block until child threads exit!
}
for(i=0; i< 5;i++)
{
sem_destroy(&sem[i]);
}
sem_destroy(&lock);
}
Your problem is in this line:
pthread_join(threads[i], NULL); //Main thread will block until child threads exit!
It is doing exactly what your comment says - your main thread creates one thread (thread 0) and then blocks until thread 0 finishes, which it never does. So your main program never creates any more threads.
The solution is to move the pthread_join calls into another loop. i.e. create all the threads first, then wait for them all to finish.

C++ Using semaphores instead of busy waiting

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.