tags:

views:

103

answers:

3

2 threads going to use the same func().
The 2 threads should be mutually exclusive. How do I get it to work properly?
(output should be "abcdeabcde")

char arr[] = "ABCDE";
int len = 5;

void func(){
for(int i = 0; i <len;i++)
  printf("%c,arr[i]);   
}
+7  A: 

Create a mutex? Assuming you're using pthread,

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

....

void func() {
    int errcode = pthread_mutex_lock(&mutex);
    // deal with errcode...
    // printf...
    errcode = pthread_mutex_unlock(&mutex);
    // deal with errcode...
}

See https://computing.llnl.gov/tutorials/pthreads/#Mutexes for a tutorial.

KennyTM
can i do it with an elementary code??like while or if??or i must use special functions?
nisnis84
You have to use special instructions -- read about atomicity.
WhirlWind
@nisnis: No, you must use special functions. Elementary code is not thread-aware (some languages have a special `synchronize`/`lock` block that functions as a mutex, but not `while` or `if`.)
KennyTM
+1  A: 
  1. In the main thread, initialize mutex m.
  2. In the main thread, create two threads that both start in some function x().
  3. In x(), get mutex m.
  4. In x(), Call func().
  5. In x(), Release mutex m.
WhirlWind
A: 

There is a good explanation on Wikipedia how to do this on both Linux and Windows

Axel Gneiting