生成任意数量的线程

Spawning Arbitrary Number of Threads

我正在尝试编写一个程序,它会产生任意数量的线程,类似于我在 中的代码,它使用进程来完成我想要完成的事情,到目前为止我有以下代码,目前我收到了很多警告,但我真的很想知道我是否正在接近我正在尝试做的事情。

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

void *runner(void *param); //the thread

int main(int argc, char *argv[]) {
  pthread_t tid = gettid();
  pthread_attr_t attr;

  if (argc != 2){
    fprintf(stderr, "Usage: a.out <integer value>\n");
    return -1;
  }

  if (atoi(argv[1]) < 0) {
    fprintf(stderr, "Argument %d must be non negative\n", atoi(argv[1]));
    return -1;
  }

  printf("My thread identifier is: %d\n", tid);

  // default attributes
  pthread_attr_init(&attr);

  // create the thread
  pthread_create(&tid, &attr, runner, argv[1]);

  // wait for the thread to exit
  pthread_join(tid, NULL);

}

void *runner(void *param){
  //int i, upper = atoi(param);
  int i;
  srand48(gettid());
  int max = nrand()%100;

  if (max > 0){
    for (i=1; i<=max; i++){
      printf("Child %d executes iteration\n", param, i);
    }
  }
  pthread_exit(0);
}

感谢我能得到的任何指导!

1:我没有看到调用 gettid()

的函数
pthread_t tid = gettid();
srand48(gettid());

2:您不能将 pthread_t 打印为整数,它是一个结构

printf("My thread identifier is: %d\n", tid);

3:是rand(),之前没见过nrand()

int max = nrand()%100;

修正这些问题并根据需要编辑问题。

如果我理解你的objective,你想创建命令行参数指示的线程数。

(记住任何特定的 OS 只能支持固定数量的线程,这取决于 OS,所以我不会在这里验证这个数字的大小。)

以下建议代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 记录包含每个头文件的原因
  4. 检查从 C 库函数返回的错误指示,例如 pthread_create()

现在建议的代码:

#include <stdio.h>   // printf(), perror(), NULL
#include <pthread.h> // pthread_create(), pthread_join(), pthread_t
#include <stdlib.h>  // exit(), EXIT_FAILURE, atof()

void *runner(void *param); //the thread

int main(int argc, char *argv[]) 
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <integer value>\n", argv[0]);
        exit( EXIT_FAILURE );
    }

    // might want to use: `strtol()` rather than `atoi()` 
    // so can check for errors
    size_t maxThreads = (size_t)atoi(argv[1]);

    pthread_t tid[ maxThreads ];   
    for( size_t i=0; i<maxThreads; i++ )
    {
        tid[i] = 0;
    }

    // create the threads
    for( size_t i=0; i<maxThreads; i++ )
    {
        if( pthread_create( &tid[i], NULL, runner, (void *)i ) )
        { 
            perror( "pthread_create failed" );
        }
    }

    // wait for each thread to exit
    for( size_t i = 0; i<maxThreads; i++ )
    {
        // if thread was created, then wait for it to exit
        if( tid[i] != 0 )
        {
            pthread_join( tid[i], NULL );
        }
    }
}


void *runner(void *arg)
{
    size_t threadNum = (size_t)arg;
    printf( "in thread: %zu\n", threadNum );

    pthread_exit( NULL );
}

a 运行 没有命令行参数导致:(其中可执行文件被命名为:untitled

Usage: ./untitled <integer value>

a 运行 命令行参数为 10 结果:

in thread: 0
in thread: 4
in thread: 2
in thread: 6
in thread: 1
in thread: 5
in thread: 7
in thread: 8
in thread: 9
in thread: 3

这表明线程 运行 没有特定顺序