p_threads初始化中向量与数组之间的差异

问题描述 投票:0回答:1

我倾向于使用向量和智能指针,而不是数组,因为这样做更安全。问题是,当初始化为数组时,我的线程成功加入了主线程。但是,初始化为向量时并非如此。这是预期的,因为通过引用可以访问数组元素。

1。作为数组

pthread_t threads[numCPU]; // Initialised as an array

// Creating threads
for(long unsigned int i=0; i<numCPU; i++){
        rc = pthread_create(&threads[i], &attr, myfunc, (void *) args[i] );
        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Created Thread " + std::to_string(i)));
        }
}

// Joining thread
for(long unsigned int i=0; i<numCPU;i++){
      rc = pthread_join(threads[i], NULL);

        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Joined Thread " + std::to_string(i)));
}

在以下情况下,将尊重pthread_create和pthread_join的签名:

std::vector<pthread_t *> threads(numCPU);

指针向量没有意义,我可能必须管理内存。有没有更安全的创建线程的方法?

c++ arrays pthreads stdvector
1个回答
1
投票

我倾向于使用向量和智能指针,而不是数组,因为这样做更安全。

向量和智能指针并不比数组更安全。

如果要在运行时确定线程数而没有恒定的上限,则使用向量而不是数组会很有用。否则它将不会有用。

目前尚不清楚为什么要创建指针向量。

© www.soinside.com 2019 - 2024. All rights reserved.