从线程

时间:2016-10-28 14:16:19

标签: c function struct pthreads circular-buffer

我有一个像

这样的结构
typedef struct{
    int op;
    int id;
    int val;
} command_t;

command_t cmd_buffer[10];

我正在创建一堆线程来处理循环缓冲区中的struct数组。 在线程创建中,我调用函数start_thread,它调用removefrombuffer,它应该返回一个结构或者至少将一个结构传递给start_thread函数

void *start_thread (void *arg){
    int i;
    command_t item;
    getfrombuffer(item);
    ///// bunch of operations from the item removed from buffer
}

command_t getfrombuffer (command_t item){
    sem_wait(&fullpositions);
    pthread_mutex_lock(&mutex);
    item = cmd_buffer[buff_read_idx++];
    if(buff_read_idx >= 6)
        buff_read_idx=0;
    pthread_mutex_unlock(&mutex);
    sem_post(&freepositions);
    return item;    
}

不幸的是在start_thread函数调用getfrombuffer()之后,在我尝试从返回的项目执行操作或者仅仅是item.id的printf之后,它会在内存中返回一个随机的valor而不是从缓冲区中删除的值。

如何从这样的函数中正确返回结构?

2 个答案:

答案 0 :(得分:1)

问题是该项是按值传递给您的函数的。

您可以通过两种方式纠正它:

  1. 使用简单的返回值
  2. void *start_thread (void *arg){
        int i;
        command_t item = getfrombuffer();
        ///// bunch of operations from the item removed from buffer
    }
    
    command_t getfrombuffer (void)
    {
        sem_wait(&fullpositions);
        pthread_mutex_lock(&mutex);
        command_t item = cmd_buffer[buff_read_idx++];
        if(buff_read_idx >= 6)
            buff_read_idx=0;
        pthread_mutex_unlock(&mutex);
        sem_post(&freepositions);
        return item;    
    }
    
    1. 使用指针
    2. void *start_thread (void *arg)
      {
          int i;
          command_t item;
          getfrombuffer(&item);
          ///// bunch of operations from the item removed from buffer
      }
      
      void getfrombuffer (command_t *item)
      {
          sem_wait(&fullpositions);
          pthread_mutex_lock(&mutex);
          *item = cmd_buffer[buff_read_idx++];
          if(buff_read_idx >= 6)
              buff_read_idx=0;
          pthread_mutex_unlock(&mutex);
          sem_post(&freepositions);   
      }
      

答案 1 :(得分:1)

您永远不会将item函数中的*start_thread设置为任何内容。将getfromebuffer(item)更改为item = getfrombuffer(item)

另一种解决方法是将getfrombuffer更改为void类型并通过引用传递item(读取:将指针传递给item),使您的代码成为这样:

void *start_thread (void *arg){
    int i;
    command_t item;
    getfrombuffer(&item);
    ///// bunch of operations from the item removed from buffer
}

void getfrombuffer (command_t* item){
    sem_wait(&fullpositions);
    pthread_mutex_lock(&mutex);
    *item = cmd_buffer[buff_read_idx++];
    if(buff_read_idx >= 6)
        buff_read_idx=0;
    pthread_mutex_unlock(&mutex);
    sem_post(&freepositions);    
}