简体   繁体   中英

Confused about thread safe and race condition in C

The book says that we need to eliminate global or static data to be thread safe. I think that thread safe means that there is no race condition in the program. However, in the following example, it changes the local veritable "Point pt_ptr" from a non-pointer type to a pointer type"Point *pt_ptr" in order to prevent the race condition. I noticed that he uses "malloc", which means he is going to create something in the heap. And things in the heap are shared by all the threads... Since it creates something that is shared, it prevents the data race BUT will it be thread UNSAFE?

 int main(void) { pthread_t tids[NUM_THREADS]; int i; Point *pt_ptr; for (i= 0; i < NUM_THREADS; i++) { pt_ptr= malloc(sizeof(*pt_ptr)); pt_ptr->x= i; pt_ptr->y= 3 * i + 2; pthread_create(&tids[i], NULL, print_point, pt_ptr); } 

It will only be thread unsafe if more than one thread attempts to access the same memory space (variable as an example) without some thread-safety mechanism, such as mutex or semaphore. They are used to provide a blocking mechanism, so that one thread will sit and "wait" until the current owning thread is thru, at which point the 2nd thread will have the ability to access/modify the variable.

Think of them as numbers at the DMV, and you have to wait until yours is called before you can get service.

In this case, each iteration of the loop calls malloc() , creating a new block of memory that is passed only to one thread. (As J. Murray correctly pointed out.) These dynamic variables are not really global at all. You could instead write:

int main(void)
{
  pthread_t tids[NUM_THREADS];

  for ( int i = 0; i < NUM_THREADS; i++) {
    Point * const pt_ptr = malloc(sizeof(*pt_ptr));
    assert(pt_ptr);  /* TODO: Handle the out-of-memory error. */
    pt_ptr->x= i;
    pt_ptr->y= 3 * i + 2;
    pthread_create(&tids[i], NULL, print_point, pt_ptr);
  }
  /* ... */
  return EXIT_SUCCESS;
}

That version makes clearer that each iteration of pt_ptr is really a separate local variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM