2011-12-31 58 views
3

我知道你必须同步你的线程才能在多线程应用程序(其中多个线程同时尝试更改变量数据)中安全地更改全局变量内容。但是,如果使用全局数组,每个线程只使用n个元素之一,这也是必要的吗?线程中的全局数组

在此先感谢!

+0

欢迎来到SO。 – vdbuilder 2011-12-31 23:19:22

+0

如果你保证每个线程只接触一个和一个元素,那么肯定 – fge 2011-12-31 23:19:23

回答

5

如果每个线程只使用一个元素,并且数组在内存中的位置永远不会改变,那么在没有同步的情况下它是绝对安全的。

2

不,如果数据未实际共享,则不需要同步。也就是说,要小心虚假共享(在不同内核上的多个线程正在使用给定缓存行的情况下),因为即使情况似乎正常,这会导致性能下降。如果你只是从数组中读取数据,这不是一个问题。

0

如果没有线程正在改变数组,你可能认为它是线程安全的。但是,如果两个线程访问相同的数组元素,则应注意竞态条件。

0

没有必要在你的情况下同步,您必须确保的读\写操作是由一个线程元素

1

如果一个线程打算只访问一个数组元素才执行,没有必要用于任何同步。但更有可能你会改变你的想法,并希望所有的线程访问数组的所有元素。那么在这种情况下,下面的程序将会很好的引用你!

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

#define NOTHREADS 5 

/* 
The following are the critical sections. 
(1) array 
(2) array index 
*/ 
int arr[10 * NOTHREADS]; 
int aindex; 

pthread_mutex_t mutex; 

void *hello(void *thread_id) 
{ 
     int i; 
     int *id = (int *) thread_id; 

     for (i=1; i<=10 ; i++) { 
       pthread_mutex_lock(&mutex); 
       arr[aindex] = (*id)*100+ i; 
       sleep(1); 
       aindex = aindex + 1; 
       pthread_mutex_unlock(&mutex); 
     } 

     pthread_exit(NULL); 
} 

int main() 
{ 
     pthread_t tids[NOTHREADS]; 
     int ids[NOTHREADS] = {1, 2, 3, 4, 5}; 
     int ret; 
     long t; 
     int i; 

     pthread_mutex_init(&mutex, NULL);  

     for (i=0 ; i<NOTHREADS; i++) { 
       printf("%d %s - Creating thread #%d \n", __LINE__, __FUNCTION__, i); 
       ret = pthread_create(&tids[i], NULL, hello, &ids[i]); 
       if (ret) { 
         printf("unable to create thread! \n"); 
         exit(-1); 
       } 
     } 

     for (i=0 ; i<NOTHREADS; i++) { 
       pthread_join(tids[i], NULL); 
     } 

     printf("Final array : \n"); 
     for (i=0; i<50; i++) 
       printf("%d ", arr[i]); 
     printf("\n\n"); 

     pthread_mutex_destroy(&mutex); 
     pthread_exit(NULL);  

     return 0; 
}