创建N个线程

时间:2017-06-13 10:02:28

标签: c multithreading posix

我编写了以下代码来创建N个线程并打印每个线程的线程ID。

sen = "the quick brown fox jumps over the lazy dog"  
smallest=[]  
re=''  

while len(sen) >0:  

    smallest.append( min(sen))
    print(ord(min(sen)))
    re=re+min(sen)
    sen = sen[:sen.index(min(sen))]+sen[sen.index(min(sen))+1:]
    counter+=1

print(smallest) #list
print(re) #string

我传递给每个线程的参数是一个计数器i,对于每个新线程,它从0增加到n-1。 但是在输出中我看到我对所有线程的值都为零,但是不能解决,有人可以解释一下。

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


void *threadFunction (void *);

int main (void)
{

   int n=0,i=0,retVal=0;
   pthread_t *thread;

   printf("Enter the number for threads you want to create between 1 to 100 \n");
   scanf("%d",&n);

   thread = (pthread_t *) malloc (n*sizeof(pthread_t));

   for (i=0;i<n;i++){
       retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)&i);
       if(retVal!=0){
           printf("pthread_create failed in %d_th pass\n",i);
           exit(EXIT_FAILURE);        
       }
   }

   for(i=0;i<n;i++){
        retVal=pthread_join(thread[i],NULL);
            if(retVal!=0){
               printf("pthread_join failed in %d_th pass\n",i);
               exit(EXIT_FAILURE);        
            }
   }

}

void *threadFunction (void *arg)
{
    int threadNum = *((int*) arg);

    pid_t tid = syscall(SYS_gettid);

    printf("I am in thread no : %d with Thread ID : %d\n",threadNum,(int)tid);


}

1 个答案:

答案 0 :(得分:1)

问题出在以下几行:

retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)&i);

请勿传递i的地址,因为i在主要功能中不断变化。而是传递i的值并在线程函数中适当地进行类型转换并使用。

例如,传递如下的值:

retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)i);

在线程函数访问中如下:

void *threadFunction (void *arg)
{
    int threadNum = (int)arg;

    pid_t tid = syscall(SYS_gettid);

    printf("I am in thread no : %d with Thread ID : %d\n",threadNum,(int)tid);


}