开发者

pthread and private data

开发者 https://www.devze.com 2023-02-25 01:59 出处:网络
How can I use pthreads in this situation? The cod开发者_StackOverflowe receives requests from stdin and return the results based on some rules. But when I create a thread, the value of id and url is s

How can I use pthreads in this situation? The cod开发者_StackOverflowe receives requests from stdin and return the results based on some rules. But when I create a thread, the value of id and url is shared by all the threads. Example:

void * filter(void * data){
        int id;
        char url[1024];
        sscanf((char *) data, "%d %1024s", &id, url);
        sleep(id);
        printf("%s\n", url);
}

while(fgets(line, BUFFER, stdin)!=NULL)
   pthread_create(&thread, NULL, &filter, (void *) line);

--- Received from stdin

1 one 2 two 3 three 4 four 5 five

--- Output

one three four five five

-- But the results must be

one two three four five

There is a way to solve it? Thank you!


As you have it, all the threads get passed a pointer to the same data, and fgets will overwrite that data each time it is called. So your output will be a bit random, and possibly corrupt.

You can hand a copy of the line read to each thread, and have each thread free it (for example).

while (fgets(...))
  pthread_create(..., (void*)strdup(line));

In the thread procedure, you should check that the passed in data is not null (could happen if strdup failed to allocate sufficient memory for the copy), and add:

free(data);

once you're done working with it.

Having a separate (static) buffer for each thread would work too, but you'd have to know how many you're going to be starting beforehand (or do some dynamic re-allocations or something like that).


It's the line variable that is shared. You have a race condition where the line buffer is filled with the next line before the thread can process the buffer. You must allocate a new buffer to be passed to each thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消