0
votes

I'm writing a very simple code in which i need to use some threads. When I create first type of thread i pass argument with pthread_create:

 fman thread_arg;
 thread_arg.sd=sda;
 char* split = strtok(buffer, "|");
 thread_arg.wcount=atoi(split);
 split = strtok(NULL,"");
 strcpy(thread_arg.id, split);
 pthread_create(&thread_temp, NULL, registerF, &thread_arg);

And everything works fine, but in function registerF I need to do something like this:

wman thread_arg;
thread_arg.sd=foremans_fd[ix];
thread_arg.fmanix=ix;
strcpy(thread_arg.id,tmpr);
pthread_create(&thread_temp, NULL, registerW, &thread_arg);

Those arguments are structures defined by me:

typedef struct fman
{
    int sd;
    char id[100];
    int wcount;
} fman;

typedef struct wman
{
    int sd;
    int fmanix;
    char id[100];
} wman;

And when I check it by printf("%x, args) I get the same address but values are different inside. Where is my mistake?

2

2 Answers

3
votes

One likely problem is here:

 fman thread_arg;
 [...]
 pthread_create(&thread_temp, NULL, registerF, &thread_arg);

Note that the thread_arg object is located on the stack, and thus will be destroyed (and likely overwritten by other stack variables) when the function it is declared in returns.

pthread_create(), on the other hand, launches a thread that will run asynchronously with this function, which means that the thread can (and often will) run after the function you excerpted has returned, which means that by the time the thread dereferences &thread_arg, thread_arg has likely already been destroyed and that pointer is now pointing to some other data that was written into the same stack location later on.

Unless you are doing something special to make sure that the struct's lifetime is long enough to include all of the spawned thread's accesses to the struct, then the fact that this code ever works is pure luck (i.e. the scheduler just happened to schedule the thread to run and perform all of its accesses to the struct before the struct was destroyed/overwritten). You definitely can't depend on that.

In order to fix the problem, you need to either allocate the struct on the heap (so that it won't be destroyed when the function returns -- the spawned thread can then free the struct when it is done using it), or use some kind of synchronization mechanism (e.g. a condition variable) to cause the main thread to block inside your function until the spawned thread has indicated that it is done accessing the struct.

1
votes

The thread struct in the running thread is treated like a block of memory and accessed using offsets. Since your fman and wman structs have different orders (4+100+4) vs (4+4+100), it's likely that you're getting right struct but reading from different memory location, given the passed struct to this thread is fman, and it's being accessed as wman.

Try changing them both to same signature, as in, int, int, char* and it should work.