【问题标题】:Creating a new thread each time a method is called using pthread每次使用 pthread 调用方法时创建一个新线程
【发布时间】:2014-12-05 21:40:44
【问题描述】:

我想创建一个程序,每次调用特定方法时都会创建一个新线程。到目前为止,这是我的工作代码:

#define NUMBER_OF_THREADS   3

pthread_t threads[NUMBER_OF_THREADS];
pthread_attr_t attr;

void *BusyWork(void *t)
{
   int i;
   long tid;
   tid = (long)t;

   printf("Thread %ld running...\n",tid);
    // ...
    printf("Thread %ld completed...\n",tid);

   pthread_exit((void*) t);
}

void createNewThread(int number){
    printf("running createNewThread(%d)\n", number);
    pthread_t tid;
    int rc = pthread_create( &tid, &attr, BusyWork, (void *) (long)number);
    if (rc) {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
    }
}

int main(int argc, char *argv[]) {
    int i, rc;

    //Set up thread attributes
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    //Arbitary amount of calls (My real program will call the createNewThread() funcion multiple unkown amount of times)
    createNewThread(15);
    createNewThread(27);
    createNewThread(62);
    createNewThread(500);
    createNewThread(8864);
    createNewThread(99999);

    //Free attributes
    pthread_attr_destroy(&attr);

    //Wait for other threads still running
    // HOW CAN I DO THIS????
    /*for (i=0; i< NUMBER_OF_THREADS; i++){
        rc = pthread_join( ??? , NULL); //TODO
        if (rc){
            printf("ERROR: return code from pthread_join() %d\n", rc);
            exit(-1);
        }
        printf("Main: completed join with thread %d\n", i);
    }*/

    printf("Main: program completed. Exiting.\n");


    pthread_exit(NULL); // (?) Is this part nessassary as we are on the main thread and soon to exit the program 

    return 0;
}

但是,正如您在我的代码中看到的,存在一些问题!例如,我如何等待所有进程完成我正在使用的代码,因为我没有跟踪线程号。此外,当一个线程“BusyWork”完成后,它不会自行清理并作为孤立进程离开。

我的一个想法是使用向量来跟踪每个线程号,然后将其用于 main 末尾的最终连接。然而问题是数组列表很容易变得非常大,即使线程完成也永远不会缩小。

【问题讨论】:

    标签: c multithreading pthreads pthread-join


    【解决方案1】:

    分离线程,不要连接它们。在创建线程之前,增加一个受互斥体保护的计数器。在线程终止之前,获取互斥锁并递减计数器。现在您知道当计数器读数为零时所有线程都已完成。如果您愿意,可以使用条件变量使计数器可等待。

    【讨论】:

    • 大卫,您的个人资料中有错字:crytpo-currency
    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多