How to spawn n threads?

前端 未结 3 965
温柔的废话
温柔的废话 2021-01-12 04:12

I\'m trying to write a multi-threaded program, the number of threads based on command-line input, and so I can\'t hard-code pre-declared threads. Is this a valid way of doin

3条回答
  •  余生分开走
    2021-01-12 05:16

    What's in the first cycle? Does it set the array elements to uninitialized value?

    So i think that's what you need:

    int threads = 5, i = 0, ret = -1;
    
    pthread_t * thread = malloc(sizeof(pthread_t)*threads);
    
    for (i = 0; i < threads; i++) {
    
        ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
    
        if(ret != 0) {
            printf ("Create pthread error!\n");
            exit (1);
        }
    }
    

    It spawns threads threads, starting foobar_function in each. And you have (if everything goes well:)) their ids in thread array. So for example you can cancel second thread by calling pthread_cancel(thread[1]) etc.

提交回复
热议问题