I'm trying to do a simple program that prints values using threads to test POSIX pthreads because I haven't used them before. The thing is that I know in a general way what's happening and how treads work, but I'm completely clueless about them working with pointers and references.
This is my program:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <mutex>
std::mutex m;
void* thread1(void* n)
{ m.lock();
int* number = static_cast<int*>(n);
(*number)++;
std::cout << "THREAD 1: " << *number << std::endl;
sleep(1);
m.unlock();
return number;
}
void* thread2(void* n)
{ m.lock();
int* number = static_cast<int*>(n);
(*number)++;
sleep(1);
std::cout << "THREAD 2: " << *number << std::endl;
m.unlock();
return number;
}
int main(void)
{ pthread_t t1, t2;
int i = 0;
int* n;
while (i < 10)
{ pthread_create(&t1, nullptr, thread1, &i);
pthread_create(&t2, nullptr, thread2, &i);
pthread_join(t2, reinterpret_cast<void**>(&n));
pthread_join(t1, reinterpret_cast<void**>(&n));
//i = *n;
}
}
The output should be the following:
THREAD 1: 1
THREAD 2: 2
THREAD 1: 3
THREAD 2: 4
THREAD 1: 5
THREAD 2: 6
But instead it's this one:
THREAD 1: 2050832128
THREAD 2: 1
THREAD 1: 2050832128
THREAD 2: 2
THREAD 1: 2050832128
THREAD 2: 3
(THREAD 1 repeats a random number for ever
but THREAD 2 does what it should.)
I know it has to do with the way I'm managing my variables, but don't know how to fix it.
EDIT 1: Added some Mutex functionalities and commented i = *n
to see how the numbers came out.
EDIT 2: Changed *number++
to (*number)++
in void* thread1(void*)
and now everything works properly.
All the information about Mutex you need to understand this post is in this other post.