Created
September 5, 2021 05:02
-
-
Save seyyedaliayati/9f1f0aa386081d86182554c02495ab20 to your computer and use it in GitHub Desktop.
Simple pthread race condition in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <cstdlib> | |
#include <iostream> | |
using namespace std; | |
int x = 0; | |
void *PrintHello(void *threadid) { | |
long tid; | |
tid = (long)threadid; | |
x++; | |
cout << "Hello World! Thread ID, " << tid << endl; | |
pthread_exit(NULL); | |
} | |
pthread_t load_data_in_thread(long id) { | |
pthread_t thread; | |
void *arg = (void *)id; | |
int rc = pthread_create(&thread, NULL, PrintHello, arg); | |
if (rc) { | |
cout << "Error:unable to create thread," << rc << endl; | |
exit(-1); | |
} | |
return thread; | |
} | |
int main() { | |
pthread_t thread1, thread2; | |
cout << "main() : creating thread 1 " << endl; | |
thread1 = load_data_in_thread(1); | |
cout << "main() : creating thread 2 " << endl; | |
thread2 = load_data_in_thread(2); | |
pthread_join(thread1, 0); | |
// pthread_join(thread2,0); | |
cout << "Final value of x: " << x << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment