I'm still very new with multithreading(pthread) and I'm still trying to familiarize with this. Right now, I have the following code that calculate the sum.
#include <iostream>
#include <pthread.h>
#include <ctime>
usingnamespace std;
using ms = chrono::milliseconds;
using get_time = chrono::steady_clock;
pthread_mutex_t mut;
int sum = 0;
void *add(void *);
int main()
{
pthread_t thread[10];
int num;
long count;
cout<< "Enter the number of thread (1-10): ";
cin >> num;
cout << "Enter the number to count to: ";
cin >> count;
for (int x = 0; x < num; x++)
{
pthread_create(&thread[x], NULL, add, (void*) count);
}
for (int x = 0; x < num; x++) {
pthread_join(thread[x], NULL);
}
cout << sum << endl;
return 0;
}
void *add(void *count){
long num;
num = (long) count;
pthread_mutex_lock(&mut);
for(long x=0; x<= num; x++)
{
sum+=x;
cout<< sum << '\t'<< x << endl;
}
pthread_mutex_unlock(&mut);
pthread_exit(NULL);
}
When I run the program, It doesn't output as what I think it would be.
Output example:
Enter the number of thread (1-10): 5
Enter the number to count to: 1
00000 00000
12345 1111
1
5
It looks so disorganize, I have no idea what's wrong with this code. I expected the code output to look something like this:
1 1
2 1
3 1
4 1
5 1