C中的Pthreads和共享内存

时间:2014-11-15 22:16:17

标签: c multithreading pthreads shared-memory

有谁能告诉我为什么我的共享内存数据结构(使用sys / shm.h实现)没有被pthreads正确读取?这是我的问题的编辑版本,代码量减少了。希望它更容易导航。

最初,被引用的结构是在共享内存空间中创建的,因此两个不同的应用程序可以读取和写入它。目标:让一个应用程序更新共享结构,另一个应用程序使用pthreads读取它。到目前为止,一切事情都在发挥作用。除了pthread之外,两个应用程序都可以读写共享内存。他们似乎没有拿起改良的共享结构?

下面是代码概述。它基于基本的运行时系统,但并不过分复杂。在pthreads中执行的函数是:

void* do_work(void *p)

共享结构是:

typedef struct WL_CTRL_T

目前我正在尝试的是打印出数组的元素。最初所有元素都设置为true。在执行的中途,使用GDB停止进程,我使用其他应用程序从外部更新结构,通过将元素0和1更改为false,然后继续执行该过程。在此我还通过顺序代码从每个应用程序打印出阵列的状态,打印输出正确。但是,当线程被设置为关闭时,它们会打印出数组的原始状态,所有这些都是真的...

结构包含一个结构数组,其中活动的bool字段由pthread

读取

我尝试了很多方法来尝试纠正这个问题,但没有快乐。

任何建议表示赞赏,谢谢:-)

/*controller api.h*/

typedef struct WL_CTRL_T
{
  int targetNumThreads;
  int sizeBuf;
  int numEntries;
  int nextIdx;
  thread_state_control_t volatile thread_state_control[THREAD_NUM];
  mon_entry_t buffer[];
} wl_ctrl_t;

typedef struct THREADPOOL_T
{
  int num_threads;
  int qsize;
  pthread_t *threads;
  todo_t *qhead;
  todo_t *qtail;
  pthread_mutex_t qlock;
  pthread_cond_t q_not_empty;
  pthread_cond_t q_empty;
  int shutdown;
  int dont_accept;
}threadpool_t;

typedef struct TODO_T
{
  void (*routine) (void*);
  void * arg;
  int lock;
  struct todo_t* next;
} todo_t;

分配给pthread的函数

/********************************************************************
*
* do_work:
*
*      this is the reusable thread, assigned work via the dispatch
*      function.
*
********************************************************************/

void* do_work(void *p) 
{  
  int c = 0;
  thread_args_t *thread_args = (thread_args_t*)p; 
  threadpool_t *pool = thread_args->threadpool;
  todo_t* workload;
  wl_ctrl_t volatile *wcc = thread_args->wl_ctrl;

  while(1) 
  {
    pool->qsize = pool->qsize;

    /* while work que is empty, spinlock */
    while( pool->qsize == 0)  
    {   
      if(c<1)
       printf("thread: %d spin-lock \n", thread_args->thread_id);
      c++; 
  }   

  /* update the threadpool, minus current workload */
  workload = pool->qhead;    
  pool->qsize--;    
  if(pool->qsize == 0)  
  {   
    pool->qhead = NULL;
    pool->qtail = NULL;
  }   
  else 
  {   
    pool->qhead = workload->next;
  }   

  /* execute workload */
  (workload->routine) (workload->arg);  
  free(workload);

  /* check this threads wait state */
  printf("In thread: %d\n",wcc->thread_state_control[thread_args->thread_id].active);                    
  }
}

0 个答案:

没有答案