2016-12-14 6 views
0

Я новичок в теме темы, и я хочу создать процесс и темы. Однако я не смог передать свою ценность нитью.Не удалось передать значение в поток в C

Пожалуйста, дайте мне знать, что не так в моем коде.

Когда я компилирую я получил следующее сообщение об ошибке:

warning: passing argument 2 of ‘pthread_create’ makes pointer from integer without a cast [-Wint-conversion]

Вот мой код:

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <sys/fcntl.h> 
#include <pthread.h> 
/////////////////////////// 

void *print_fun(int *id) { 

    printf("Thread #%d is using the print function now! \n",a); 
} 

int main() 
{ 
    int pid1,pid2,pid3; 
    pthread_t t1,t2; 

    pid1=fork(); 
    if (pid1==0) 
    {//child #1 
     pthread_create(&t1,1,print_fun,NULL); 
     printf("The child of process #1 has been created!!\n"); 
    } 
    if (pid1>0) 
    {//Father #1 
     printf("The process #1 has been created!!\n"); 
     pid2=fork(); 
     if (pid2>0)//Father #2 
     { 
      printf("The process #2 has been created!!\n"); 
      pid3=fork(); 
      if (pid3>0)//Father #3 
      { 
       printf("The process #3 has been created!!\n"); 
      } 
      else 
      { 
       printf("There is error in the third fork!\n"); 
      } 
     } 
     else if(pid2==0)//child #2 
     { 
      pthread_create(&t1,2,print_fun,NULL); 
      printf("The child of process #2 has been created!!\n"); 
     } 
     else 
     { 
      printf("There is error in the second fork!\n"); 
     } 
    } 
    else 
    {//error 
     printf("There is error in the first fork!\n"); 
    } 

    pthread_exit(NULL); 
} 
+2

Прочитать manpage. ['pthread_create'] (http://man7.org/linux/man-pages/man3/pthread_create.3.html) хочет указать указатель на' const pthread_attr_t' во втором аргументе, и вместо этого вы предоставляете 'int'. –

+0

Я думаю, вы также хотите определить переменную 'a' в' print_fun'. Вы также пропустите проверку, 'pid3 == 0'. –

+0

@MarekKlein: Я сделал это. Благодаря :) –

ответ

2

Вы, наверное, хотите:

pthread_create(&t1, NULL, print_fun, (void*)2); 

вместо:

pthread_create(&t1, 2, print_fun, NULL); 

Второй аргумент pthread_create является указателем на структуру pthread_attr_t или NULL.