【问题标题】:Global arrays in threads线程中的全局数组
【发布时间】:2011-12-31 23:16:28
【问题描述】:

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

提前致谢!

【问题讨论】:

  • 如果你保证每个线程只接触一个和一个元素,那么确定

标签: c multithreading thread-safety


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不,如果数据实际上没有共享,则不需要同步。也就是说,请注意错误共享(不同内核上的多个线程正在使用给定的缓存行),因为即使事情看起来工作正常,这也会导致性能下降。如果您只是从数组中读取数据,这不是什么大问题。

    【讨论】:

      【解决方案3】:

      如果一个线程只访问一个数组元素,则不需要任何同步。但是您更有可能改变主意并希望所有线程访问数组的所有元素。所以在这种情况下,下面的程序将是你的一个很好的参考!

      #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;
      }
      

      【讨论】:

        【解决方案4】:

        如果没有线程正在更改数组,您可能会认为它是线程安全的。但是,如果两个线程访问同一个数组元素,您应该注意竞争条件。

        【讨论】:

          【解决方案5】:

          在你的情况下不需要同步,你必须确保读\写操作只由一个元素的一个线程执行

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-11-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多