我正在尝试学习C++中的多线程。我试图将向量的元素作为参数传递给pthread_create。但是,它并没有按预期工作。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <vector>
using namespace std;
void *count(void *arg)
{
int threadId = *((int *)arg);
cout << "Currently thread with id " << threadId << " is executing " << endl;
pthread_exit(NULL);
}
int main()
{
pthread_t thread1;
vector<int> threadId(2);
threadId[0] = 99;
threadId[1] = 100;
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[0] << endl;
exit(-1);
}
pthread_t thread2;
retVal = pthread_create(&thread2, NULL, count, (void *)&threadId[1]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[1] << endl;
exit(-1);
}
pthread_exit(NULL);
}
我得到的输出是:
当前正在执行线程 ID 为 99。
当前正在执行线程 ID 为 0。
然而,根据我的理解,它应该是:
当前正在执行线程 ID 为 99。
当前正在执行线程 ID 为 100。
这里有什么我忽略的吗?
std::thread
是否有特别的原因?它的接口更好。 - HolyBlackCat