Pthread Multithreading

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  #include <iostream>
#include <pthread.h>
#include <ctime>
using namespace 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

Will appreciate any help. Thank you.
Last edited on
Topic archived. No new replies allowed.