help with id

Hi,

i have the code :
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
#include <iostream>
#include <pthread.h>

using namespace std;

struct arg_struct {
    int arg1;
    int arg2;
	int id;
};

void *print(void *arguments)
{
    struct arg_struct *args = static_cast<struct arg_struct *>(arguments);
    cout << args -> arg1 << "\n";
    cout << args -> arg2 << "\n";
    cout << args -> id << "\n";
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t thr;
    struct arg_struct args;
    args.arg1 = 10;
    args.arg2 = 20;
	
    pthread_t thread[4];
	
    args.id = 0;
    for(int i=0;i<4;i++){
         pthread_create(&thread[i], NULL, print, (void *)&args);
         args.id++;
    }

    for(int i=0;i<4;i++)
         pthread_join(thread[i], NULL);
	
    return 0;
}


how to view the correct thread id in the function print using the struct too ?
Can this be done directly via the pthread_create function ? How ?
I mean that the answer i receive from the function print is thread id equal to 4 for all threads, which is wrong. The correct is to have the treads id 0,1,2,3 and not only 4.

Any help please ?
All four threads have a pointer to the same 'args', so they're all showing the same value of 4, which is what your for loop has incremented it to.

Cheers,
Jim
Topic archived. No new replies allowed.