Domanda

I'm starting to play with threads (pthreads) and I don't understand how to predict how they work. In other words, I have this really simple program that just increments a variable :

#include <stdio.h>
#include <pthread.h>

int counter = 0;

void *MyThread(void *arg) {
    int i;
    for (i = 0; i < 10000; i++) {
        counter++;
    }

    return NULL;
}

int main() {
    pthread_t tid[40];
    int i;
    void *val;
    void *MyThread(void *);

    for (i = 0; i < 40; i++) {
        pthread_create(&tid[i], NULL, MyThread, NULL);
    }

    for (i = 0; i < 40; i++) {
        pthread_join(tid[i], &val);
    }

    printf("Counter = %d\n", counter);
    return 0;
}

I don't understand why it gives random results! If I create (and join) 40 threads, how come they don't all finish thier work?

È stato utile?

Soluzione

Incrementing is not an atomic operation. As such each thread is likely to corrupt the counter value if they access it simultaneously. If you wish for multiple threads to access a variable at once you must only use atomic operations or wrap the operations in a mutex or semaphore.

The simplest fix you could make, assuming you are using gcc would be to replace the line

counter++;

with

__sync_fetch_and_add(&counter, 1);

This will replace the increment with an atomic increment and hopefully the program will execute correctly.

You can find much more information about atomic operations here: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html

Altri suggerimenti

All your threads are modifying the same global variable (counter). You should read the response to this question

Global variables and threads

For POSIX threads, you would need to use a mutex and you can find an example on how to here http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzahw%2Frzahwe18rx.htm

They all finish their work. Still, it might not reflected in counter due to concurrency issues.
Specifically, it is not defined when or if at all any thread sees updates to counter in your example, because you do not synchronize them.

You are using a global variable 'counter'. This variable is being incremented independently without synchronization by all the threads you create.

You cannot have a shared variable(in your case - counter) be manipulated by multiple threads at the same time with out proper synchronization mechanism in place. Otherwise you would have a race condition. which leads to undefined behaviour.

You ought to use pthread mutexes to lock your code which aren't atomic and alter shared variables and which can be executed independently by threads.

You should be aware of thread safety when writing multithreaded code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top