2014-12-05 2 views
1

pthread를 만들려고하는데 인수를 만드는 데 필요한 인수가 혼란 스럽습니다.pthread_create가 인수를 허용하지 않습니다.

pthread에 대한 입력 함수에 여러 인수를 전달하려고하고 있는데이를 구조체에 캡슐화했습니다. 그러나 pthread_create은 허용하지 않습니다. 여기

내 코드의 관련 부분과 같습니다 Customer_Spawn_Params 구조체 여기

Customer_Spawn_Params *params = (Customer_Spawn_Params*) malloc(sizeof(Customer_Spawn_Params)); 
    params->probability = chance; 
    params->queue = queue; 

    pthread_t customer_spawn_t; 
    if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, &params)) { 
    } 

하고 마지막으로

typedef struct { 
     Queue *queue; 
     double probability; 
} Customer_Spawn_Params; 

, 여기 Customer_Spawn_Params 구조체에 대한 포인터를 받아들이는 enqueue_customers()입니다 :

void *enqueue_customers(Customer_Spawn_Params *params) { 
     int customer_id = 0; 
     double probability = params->probability; 
     Queue *queue = params->queue; 
     while(true) { 
       sleep(1); 
       bool next_customer = next_bool(probability); 
       if (next_customer) { 
         Customer *customer = (Customer*) malloc(sizeof(Customer)); 
         customer->id = customer_id; 
         enqueue(queue, customer); 
         customer_id++; 
       } 
     } 
     return NULL; 
} 
+0

'그러나, pthread_create는 그것을 받아들이지 않습니다 .'...이 결론에 어떻게 도달 했습니까? –

+0

'pthread_create'를 호출 할 때 마지막 인자 (쓰레드 함수에 대한 인자)를 포인터 *로 전달합니다. 스레드 함수를 변경하지 않으면 [* undefined behavior *] (http://en.wikipedia.org/wiki/Undefined_behavior)가됩니다. –

+0

매개 변수를 (void *)로 캐스팅하고 스레드 proc가 void를 허용해야합니다. * – dvhh

답변

2

가 포인트 1.

if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, &params))

변화

if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, params))에 있어야한다.

params은 포인터 자체이기 때문에. 포인트 2

:

void *enqueue_customers(Customer_Spawn_Params *params) 

이 함수에서

void *enqueue_customers(void *params) 

해야한다 또한

, 당신은

, 예를 들어, 다시 실제 포인터를 캐스트해야
void *enqueue_customers(void *params) 
{ 
    Customer_Spawn_Params *p = params; 
+0

'void *'를 무언가에 던지십시오. 이것은 완전히 불필요하며 실제로 문제를 숨길 수 있습니다. –

+0

@JensGustedt OK 각하, 감사합니다. 좀 더 정교한 게시물을 정교하게 만들거나 링크 할 수 있습니까? 즐거움과 함께 –

+0

:) https://gustedt.wordpress.com/2014/04/02/dont-use-casts-i/ –

2

귀하의 기능 enqueue_customers에 올바른 프로토 타입이 없습니다. 그것은

void *enqueue_customers(void* p) { 
    Customer_Spawn_Params *params = p; 
    ... 
관련 문제