2015-10-17 55 views
0

以下是我想实现线程数组的一个c程序。 有两个线程函数。我想在每个函数内发送一个int值。但是代码没有给出任何输出。 示例程序:实现线程数组

#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <unistd.h> 


void * threadFunc1(void * arg) 
{ 

    int id = *((int *) arg); 
    printf("Inside threadfunc2 for thread %d",id) 
} 

void * threadFunc2(void * arg) 
{ 
    int i= *((int *)arg); 
    printf("Inside threadfunc2 for thread %d",i) 

} 

int main(void) 
{ 

    pthread_t thread[10]; 

    for(int i=0;i<10;i++) 
    { 

     pthread_create(&thread[i],NULL,threadFunc1,(void*)&i); // want to send the value of i inside each thread 

     pthread_create(&thread[i],NULL,threadFunc,(void*)&i); 
    } 


    while(1); 
    return 0; 
} 

代码中有什么问题吗?

+0

如果您使用C++,请使用'std :: thread',这是一回事。然后,你问题中的C标签也是错误的。在任何情况下,它都缺少有关代码在执行时的作用以及您的期望。我的水晶球告诉我,你应该尝试使用'%p'格式说明符输出传递给线程函数的指针,或者只是将其传递给'std :: cout'。 –

+0

请参阅[@UlrichEckhardt](http://stackoverflow.com/questions/33183877/implementing-an-array-of-thread#comment54174239_33183877)的评论。这就是为什么每个人都会告诉你**不要用C++标记**来标记c问题。 –

+0

你能分享获得的输出吗? –

回答

1

只需在线程函数内的printf中的字符串中添加一个“\ n”终止符。这将强制flushing the output buffer

您粘贴的代码中也存在一些语法错误,但您可能很容易将其计算在内。您可以使用pthread_join()而不是while (1); ...

0

线程[i]应该是pthread_create返回的新线程的唯一标识符(它将保存新创建的线程的线程ID)。 ,在这里提供的代码中,线程[i]被第二个pthread_create()覆盖。一种方法可以是具有的pthread_t为threadFunc1和ThreadFunc中的单独的阵列如下:

pthread_t thread_func[10]; 
pthread_t thread_func1[10]; 

对于传递的数据类型为int的自变量到线程,则需要在堆上分配一个int并把它传递给pthread_create()如下:

for(i=0;i<10;i++) 
{ 
    int *arg = malloc(sizeof(*arg)); 
    *arg = i; 
    pthread_create(&thread_func[i],NULL,threadFunc,(void*)arg); 
    int *arg1 = malloc(sizeof(*arg1)); 
    *arg1 = i; 
    pthread_create(&thread_func1[i],NULL,threadFunc1,(void*)arg1); 
} 

确保以释放从堆存储器中,如下所示的各线程函数:

void *threadFunc(void *i) { 
    int a = *((int *) i); 
    printf("threadFunc : %d \n",a); 
    free(i); 
} 
void *threadFunc1(void *i) { 
    int a = *((int *) i); 
    printf("threadFunc1 : %d \n",a); 
    free(i); 
} 

此外,使用在pthread_join如下项tead of while end:

for (i=0;i<10;i++) 
{ 
    pthread_join(thread_func[i],NULL); 
    pthread_join(thread_func1[i],NULL); 
}