看來這個問題getsaskedfrequently,但我沒有得出任何明確的結論。我需要決定是否我應該有點幫助實現訪問時,鎖定代碼/修改全局變量時,我有(或必須的!):在文件範圍內 從單個工作線程更新全局變量:我需要互斥鎖嗎?
- 全局變量線程讀取/從主進程線程調用訪問功能並返回這些全局
寫入全局變量
更具體地說,我正在編寫一個C++庫,它使用網絡攝像頭跟蹤紙張上的對象 - 計算機視覺是CPU密集型的,因此性能至關重要。我有一個單個工作線程在Open()
函數中被分離出來。該線程處理所有的對象跟蹤。當調用一個Close()
函數時,它被終止(間接帶有全局標誌)。
這感覺就像我只是要求內存損壞,但我沒有觀察到死鎖問題,也沒有遇到任何從這些訪問函數返回的錯誤值。經過幾個小時的研究,我得到的一般印象是,「呃,可能吧,無論如何,,。」如果我確實應該使用互斥體,爲什麼我還沒有遇到任何問題呢?
這裏是我目前的計劃過於簡單化:
// *********** lib.h ***********
// Structure definitions
struct Pointer
{
int x, y;
};
// more...
// API functions
Pointer GetPointer();
void Start();
void Stop();
// more...
實現看起來像這樣...
// *********** lib.cpp ***********
// Globals
Pointer p1;
bool isRunning = false;
HANDLE hWorkerThread;
// more...
// API functions
Pointer GetPointer()
{
// NOTE: my current implementation is actually returning a pointer to the
// global object in memory, not a copy of it, like below...
// Return copy of pointer data
return p1;
}
// more "getters"...
void Open()
{
// Create worker thread -- continues until Close() is called by API user
hWorkerThread = CreateThread(NULL, 0, DoWork, NULL, 0, NULL);
}
void Close()
{
isRunning = false;
// Wait for the thread to close nicely or else you WILL get nasty
// deadlock issues on close
WaitForSingleObject(hWorkerThread, INFINITE);
}
DWORD WINAPI DoWork(LPVOID lpParam)
{
while (isRunning)
{
// do work, including updating 'p1' about 10 times per sec
}
return 0;
}
最後,該代碼被從外部可執行文件調用。像這樣的東西(僞代碼):
// *********** main.cpp ***********
int main()
{
Open();
while (<esc not pressed>)
{
Pointer p = GetPointer();
<wait 50ms or so>
}
Close();
}
是否有我應該採取的另一種方法?這個非問題問題讓我今天非常緊張: - /我需要確保這個庫是穩定的並且返回準確的值。任何有識之士將不勝感激。
感謝
也許有些基礎會有所幫助:http://en.wikipedia.org/wiki/Readers-writer_lock – JoshD 2010-10-21 00:07:21
感謝大家的出色答案,尤其是暗示我對讀者 - 作家互斥的想法(似乎這些概念沒有提供)在大學裏得到很多報道......)。我最終使用boost :: shared_mutex來鎖定對主程序循環中修改的每個全局變量的訪問。 (請參閱http://stackoverflow.com/questions/989795/example-for-boost-shared-mutex-multiple-reads-one-write)。如果有人感興趣,我可以提供我最終解決方案的一個簡單例子。 – 2010-10-22 22:36:51