2012-04-23 107 views
-2

在运行时,如何创建线程?运行时线程创建

我会从标准输入 - 终端采取#线程,然后我会根据这个数字创建线程。但是,如何?

Ex: 
    input : N,    N is integer 

    in main function 

       create N thread 

编辑:平台的Linux

+1

是的,可以。但究竟如何做到这一点很大程度上取决于你使用哪个系统来运行这个系统。线程不是C标准的一部分。你在使用哪个系统? – 2012-04-23 07:22:52

回答

2

是,线程(如果我们假设我们使用的并行线程)与呼叫在pthread_create创建的,你可以调用从一个循环。

下面是创建N个线程C函数的开头:

int start_N_threads(int N) { 
    pthread_t threads[N]; 
    printf("Starting %d thread(s)...\n", N); 
    for (int i = 0; i < N; ++i) { 
     if (pthread_create(&threads[i], NULL, thread_body, (void*)&results[i]) != 0) { 
      printf("Couldn't create thread %d.\n", i); 
     } 
    } 
    printf("The %d thread(s) are running.\n", N);