数组指针如何在线程中工作?

时间:2017-11-21 22:20:08

标签: c pthreads

我是pthreads的新手,并试图理解它。我编写了一个创建新线程的程序,它创建了另一个线程......依此类推至threads_count!= 10;我想将2个参数作为数组传递给线程。当我从主打电话时 - 它有效。当我在函数内部调用它时,我会变成类似

的东西
Sleeping for 4 sec before thread creation
Sleeping for 32767 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation

我是否将函数内部的参数传递给新线程错误?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX_THREADS 10 

int threads_count = 0;



void* SpawnTwoThreads(void *args) {
    pthread_t t1;
    pthread_t t2;  

    int* thread_args = (int*)args;
    printf("Sleeping for %d sec before thread creation\n", thread_args[1]);
    sleep(5); 
    if(threads_count < MAX_THREADS) {
        threads_count++;
        thread_args[1] = rand() % 10;
        pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args);
    }
    pthread_exit(NULL);
}

int main(void) {
    pthread_t t1;
    int t1_wait_time;

    srand(time(NULL));

    int start_args[2];
    start_args[0] = 0;
    start_args[1] = rand() % 10;
    pthread_create(&t1, NULL, SpawnTwoThreads, &start_args);

    printf("In main: waiting for all threads to complete\n");
    pthread_join(t1, NULL);
    printf("Overall waittime is %d\n", wait_time_overall);
    pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:1)

pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args);里面SpanTwoThreads()你传递了一个双指针,而你应该只使用thread_args作为最后一个参数(因为它已经是一个指针) 。在main()函数中,您不会看到此问题,因为start_args被声明为数组,所以放一个&amp;它前面的符号与使用数组本身的名称相同。