VS rand () problem with pthread-win32

I am entering a strange problem in pthread programming I have compiled the following code in vs2005 with pthread-w32

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <pthread.h>
#include <windows.h>

pthread_mutex_t lock;

void* thread1(void *) {
  int r1;
  while(true) {
    pthread_mutex_lock(&lock); // rand is maybe a CS
    r1 = rand() % 1500;
    pthread_mutex_unlock(&lock);
    Sleep(r1); printf("1:%d\n", r1);
  }
  return NULL;
}

void* thread2(void *) {
  int r2;
  while(true) {
    pthread_mutex_lock(&lock);
    r2 = rand() % 1500;
    pthread_mutex_unlock(&lock);
    Sleep(r2); printf("2:%d\n", r2);
  }
  return NULL;
}

int main() {
  srand((int)time(NULL));
  pthread_mutex_init(&lock, NULL);

  pthread_t tc_p, tc_v;
  pthread_create(&tc_p, NULL, thread1, NULL);
  pthread_create(&tc_v, NULL, thread2, NULL);

  pthread_join(tc_p, NULL);
  pthread_join(tc_v, NULL);

  pthread_mutex_destroy(&lock);

    return 0;
}

      

and the output looks like this

2:41
1:41
1:467
2:467
1:334
2:334
1:1000
2:1000

      

it is exactly like rand (), returns the same result in each of the two calls and I have srand (), but the result does not change every time I run the program

I am very new to multithreading programming and I have heard of rand () which is not thread safe. but I still can't figure out if the program above is wrong or if the rand () function has some problems in it.

+1


a source to share


2 answers


rand

is only pseudo-random and will return the same sequence every time. srand

only works on the current thread, so calling it on the main thread does not affect your worker threads.

You need to call srand

from each thread with a different value for each thread, for example in your functions thread1

and thread2

:



srand((int)time(NULL) ^ (int)pthread_getthreadid_np());

      

+4


a source


Try using this instead rand_s()

, it's thread safe. See here . Of course it is not portable.



+1


a source







All Articles