2017/05/12

[C/C++] Thread Pool的實作 及 pthread_create參數的傳遞

假設一個使用情境,今天有10個人,每個人從1-10之間拿一個數字,隨機順序的累加。

設計上,可以利用pthread pool的方式來實作,用struct的方式來綁定一個thread,包含人名及所包含的值。然後各thread去累加一個global的變數。





thread_parameter的資料結構: 儲存pthread id, name和value
struct thread_parameter
{
 pthread_t student_thread;
 char *student_name;
 int value;
};

利用pthread_create傳遞參數,其中pthread_create的定義為
#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

Compile and link with -pthread.
利用第四個參數void *arg,以指標的方式把struct thread_parameter傳遞進去。寫法就會變成(void *)&thread_parameters[i];因為是一個thread pool,取array指標的方式就得用&array[i]。

怎麼取指標可以參考這篇
[C/C++] 幾個容易搞混的指標pointer用法整理 之中的 -- 3.call by reference

程式碼: main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define THREAD_MAX 10

int count = 0;

struct thread_parameter
{
 pthread_t student_thread;
 char *student_name;
 int value;
};
struct thread_parameter thread_parameters[THREAD_MAX];

void *increase_thread(void *data)
{
 struct thread_parameter *now_thread = (struct thread_parameter*)data;
 printf("From %s: added by %d\n", 
  now_thread->student_name, now_thread->value);

 count = count + now_thread->value;
 printf("%s: count is %d\n\n", 
  now_thread->student_name, count);

 pthread_exit(NULL);
}

int main(void)
{
 int i;
 char *name[THREAD_MAX] = { "Adrián", "Bárbara", "César", "Damián", "Flavia", 
    "Gastón", "Hortensia", "Inés", "Jerónimo", "Lucía"};
 int value[THREAD_MAX] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 // initialize thread pools
 for(i=0; i<THREAD_MAX; i++) {
  thread_parameters[i].student_name = strdup(name[i]);
  thread_parameters[i].value = value[i];
 }

 for(i=0; i<THREAD_MAX; i++) {
  if (-1 == pthread_create(&(thread_parameters[i].student_thread), 
   NULL, increase_thread, (void *)&thread_parameters[i])) {
   printf("pthread_create error\n");
   return -1;
  }
 }

 while(1) {};

 return 0;
}

執行結果
可以看到累加結果為55,但累加過程是隨機的。

沒有留言:

張貼留言