您好,登錄后才能下訂單哦!
在C++中實(shí)現(xiàn)一個(gè)線程安全的Array類,可以通過使用互斥鎖來保護(hù)對數(shù)組元素的訪問。以下是一個(gè)示例實(shí)現(xiàn):
#include <iostream>
#include <vector>
#include <mutex>
class ThreadSafeArray {
private:
std::vector<int> data;
std::mutex mutex;
public:
ThreadSafeArray(int size) : data(size) {}
int& operator[](int index) {
std::lock_guard<std::mutex> lock(mutex);
return data[index];
}
void resize(int size) {
std::lock_guard<std::mutex> lock(mutex);
data.resize(size);
}
int size() {
std::lock_guard<std::mutex> lock(mutex);
return data.size();
}
};
int main() {
ThreadSafeArray array(5);
// 使用線程安全的Array類
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
// 獲取數(shù)組大小
std::cout << "Array size: " << array.size() << std::endl;
return 0;
}
在上面的示例中,我們定義了一個(gè)ThreadSafeArray類,其中包含一個(gè)std::vector作為數(shù)據(jù)存儲,并使用std::mutex來保護(hù)對數(shù)組元素的訪問。通過在數(shù)組操作中使用std::lock_guardstd::mutex,可以確保在訪問數(shù)組元素時(shí)只有一個(gè)線程能夠進(jìn)行操作,從而實(shí)現(xiàn)線程安全。
在main函數(shù)中,我們創(chuàng)建了一個(gè)ThreadSafeArray對象,并演示了如何使用該類來訪問和修改數(shù)組元素,以及如何獲取數(shù)組的大小。通過這種方式,我們可以確保在多線程環(huán)境下對數(shù)組的操作是安全的。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。