c - 如何在不强制使用 c 的情况下为每个线程分配任务,即每个线程在完成第一项工作后需要执行一些工作?

标签 c pthreads

即每个线程在完成第一项工作后需要执行一些工作。每个线程都需要自动接受任务并运行代码。有人可以帮忙解决这个方法吗?

    #include <pthread.h>


    #define thread_count (4)
    pthread_t read_thread_id[thread_count ];

    float sum_Data[128]= {0,1,2,3.........128};
    float sub_Data[128]= {0,1,2,3.........128};
    float Out_Mem[128] ={0};




    void af_sum(float *a, float *b, float *c)
    {
       c=a+b;
       return 0;
    }

    void *Data_output(void *data)
    {
       int temp = (int) data;
       int k;

       if(temp==0)
       {
//assigning some task for thread 0
          for(k = 0; k < 32; k++)
          {
             af_sum(&sum_Data[k], &sub_Data[k], &Out_Mem[k]);
          }
       }
       else if(temp==1)
       {
//assigning some task for thread 1
          for(k = 32; k < 64; k++)
          {
             af_sum(&sum_Data[k], &sub_Data[k], &Out_Mem[k]);
          }
       }
       else if(temp==2)
       {
//assigning some task for thread 3
          for(k = 64; k < 96; k++)
          {
             af_sum(&sum_Data[k], &sub_Data[k], &Out_Mem[k]);
          }
       }
       else
       {
//assigning some task for thread 4
          for(k = 96; k < 128; k++)
          {
             af_sum(&sum_Data[k], &sub_Data[k], &Out_Mem[k]);
          }
       }

       return 0;

    }



    int main()
    {

       int i,k;
       for (i = 0; i < thread_count ; i++)
       {
          pthread_create (&read_thread_id[i], NULL, Data_output, (void *) i);
       }

       for (i = 0; i < AF_NUM_INSTANCE; i++)
       {
          pthread_join (read_thread_id[i], NULL);

       }

        return (0);
    }

即每个线程在完成第一项工作后需要执行一些工作。每个线程都需要自动接受任务并运行代码。

最佳答案

您可以定义一个由所有线程调用的函数来接管工作。 pick_work() 函数使用互斥体来确保每个线程获得自己独特的工作。这是伪代码:

int currWork = 0;

// Each thread calls pick_work() to figure out the work.  If the
// return value of pick_work() is < 0, the thread returns/exits.

// Returns index of work assgined to caller
// Returns -1 to indicate that there is no more work left.
int pick_work()
{
    int work_index = -1;
    pthread_mutex_lock(&mutex);
    if (currWork < MAX_WORKS) {
        work_index = currWork;
        currWork++;
    }
    pthread_mutex_unlock(&mutex);
    return work_index;
}

关于c - 如何在不强制使用 c 的情况下为每个线程分配任务,即每个线程在完成第一项工作后需要执行一些工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397758/

相关文章:

我可以在我的 c 程序中的任何地方编写预处理器指令吗?

c - 链表的问题

c - pthread_atfork 锁定习语坏了?

c - 条件变量的实现

c - 编译 C 时检测 OCaml 版本

c - 双链表随机快速排序

c - union 和位掩码,这是如何工作的?

Linux socket使用多线程发送

c - 取消引用由 pthread_join 设置的指针时的段错误

c - Linux 2.6.x 中线程的动态优先级是如何计算的?