views:

55

answers:

4

Heres my code:

void *PrintLine(void *line)
{
    printf("Line: #%s\n", (char *)line);
    pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
    char line[80];
    while(fgets(line,sizeof(line),fp))
    {
        pthread_create(&threads[rt], NULL, PrintLine, (void*)line);
    }
    fclose(fp);
}

Please dont tell me that running a thread only to print a file line doesn't make sense, I removed a lot of code so its easier to read and understand my problem.

As you would guess this code doesn't work, what should I do to be able to print/use "line" inside the thread?

A: 

Two immediately obvious problems:

  • you only have instance of line (think about it)
  • there is no guarantee that printf is thread-safe
Paul R
yea i am asking for a solution for the problems :)
jahmax
+2  A: 

You need pthread_join(3) in the main thread to wait for completion of each thread you spawned. Otherwise the main thread might end the process before other threads have a chance to do the printing (and also to make sure the stack memory you point spawned threads to is still in scope).

Edit:

Then post "real" code, or at least "working" code. We are not mind readers.

Another obvious error is that main threads overrides the buffer the other threads are supposed to be printing. There's no guarantee that at some point the string in that buffer is not zero-terminated. You really need to make a copy in the main thread before giving it to other threads.

Nikolai N Fetissov
No i dont, the code is not "real" code is just to show my problem with "line".
jahmax
+2  A: 

You're passing a pointer to line to the newly created thread, when your thread gets around to use line , perhapse fgets have written something else to it. Or perhaps it's in the middle of writing something when your thread accesses it.

You can pass a copy of the line you've read, remember to free() it when you're done with it inside you thread.

char *copy_of_line = strdup(line);
if(copy_of_line)
  pthread_create(&threads[rt], NULL, PrintLine, copy_of_line);
nos
but if I reassign *copy_of_line for each thread, will it still work? or will i need a different *copy_of_line for each thread?
jahmax
I copied it inside the thread, and after launching each thread I make it sleep for 200 milliseconds so it wont rewrite the line var before I copied it.Thanks.
jahmax
No, that still does not guarantee that the buffer is safe. You really need to make that copy in the main thread, *so only one thread is writing and reading that memory*.
Nikolai N Fetissov
A: 

Your problem is that all your threads use the same line buffer so a new line might be read before the other one is printed.

Jens Gustedt