标准的C++数据结构可以使用std::
命名空间中的容器类来实现,而pthread
互斥锁可以使用pthread_mutex_t
来创建和操作。
下面是使用标准的C++数据结构和pthread
互斥锁的示例代码:
#include
#include
#include
// 全局变量,用于线程间共享的数据结构
std::vector data;
pthread_mutex_t mutex;
void* threadFunction(void* arg) {
// 线程函数内部操作共享数据结构需要使用互斥锁保护
pthread_mutex_lock(&mutex);
// 操作共享数据结构
for (int i = 0; i < 1000; ++i) {
data.push_back(i);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
pthread_mutex_init(&mutex, NULL);
// 创建新线程
int result = pthread_create(&thread, NULL, threadFunction, NULL);
if (result != 0) {
std::cout << "Failed to create thread." << std::endl;
return 1;
}
// 主线程操作共享数据结构需要使用互斥锁保护
pthread_mutex_lock(&mutex);
// 操作共享数据结构
for (int i = 0; i < 1000; ++i) {
data.push_back(i);
}
pthread_mutex_unlock(&mutex);
// 等待子线程结束
pthread_join(thread, NULL);
// 打印共享数据结构中的元素个数
std::cout << "Data size: " << data.size() << std::endl;
pthread_mutex_destroy(&mutex);
return 0;
}
在上面的示例代码中,使用了std::vector
作为标准的C++数据结构,pthread_mutex_t
作为互斥锁。主线程和子线程都可以对data
进行操作,而通过互斥锁的保护,确保了操作的安全性。