[英]how do i lock access to a bool with a mutex?
解決了!:我在新線程中復制Map的實例並且不使用引用。
我正在學習如何使用多個線程。 為此我編寫了一個小游戲,我希望游戲在主線程中運行,並且該級別的下一個塊將被加載到另一個線程中。 為此,我在向量周圍設置一個互斥鎖,告訴加載線程接下來要加載什么。 在這個互斥鎖內部,我還有一個布爾值來告訴線程何時終止。
在Map :: Map()中初始化線程
pending_orders_mutex = SDL_CreateMutex();
can_process_order = SDL_CreateCond();
chunk_loader_thread = SDL_CreateThread(Map::chunk_loader,"chunk_loader_thread",(void*)this);
加載線程
int Map::chunk_loader(void * data)
{
Map map = *(Map*)data;
bool kill_this_thread = false;
Chunk_Order actual_order;
actual_order.load_graphics = false;
actual_order.x = 0;
actual_order.y = 0;
while (!kill_this_thread)
{
SDL_LockMutex(map.pending_orders_mutex); // lock mutex
printf("3-kill_chunk_loader_thread: %d\n", map.kill_chunk_loader_thread);
kill_this_thread = map.kill_chunk_loader_thread;
printf("4-kill_chunk_loader_thread: %d\n", map.kill_chunk_loader_thread);
if (!kill_this_thread)
{
if (map.pending_orders.size())
{
actual_order = map.pending_orders.back();
map.pending_orders.pop_back();
printf("in thread processing order\n");
}
else
{
printf("in thread waiting for order\n");
SDL_CondWait(map.can_process_order, map.pending_orders_mutex);
}
}
SDL_UnlockMutex(map.pending_orders_mutex); // unlock mutex
//load actual order
}
printf("thread got killed\n");
return 0;
}
殺死線程(主線程)
SDL_LockMutex(pending_orders_mutex); // lock mutex
printf("setting kill command\n");
printf("1-kill_chunk_loader_thread: %d\n", kill_chunk_loader_thread);
kill_chunk_loader_thread = true; // send kill command
printf("2-kill_chunk_loader_thread: %d\n", kill_chunk_loader_thread);
SDL_CondSignal(can_process_order); // signal that order was pushed
SDL_UnlockMutex(pending_orders_mutex); // unlock mutex
SDL_WaitThread(chunk_loader_thread, NULL);
控制台輸出
3-kill_chunk_loader_thread: 0
4-kill_chunk_loader_thread: 0
in thread waiting for order
setting kill command
1-kill_chunk_loader_thread: 0
2-kill_chunk_loader_thread: 1
3-kill_chunk_loader_thread: 0
4-kill_chunk_loader_thread: 0
in thread waiting for order
為什么mainthread不會在加載線程中更改“kill_chunk_loader_thread”布爾值?
首先,您應該嘗試在問題中上傳最小的完整程序。
它看起來像你設置kill_chunk_loader_thread = true
但你沒有設置map.kill_chunk_loader_thread = true
你的問題中的map
聲明部分是missig,但我猜你沒有使用對本地或全局變量的引用,或者你只是執行struct copy,所以當你改變一個結構時,另一個結構根本沒有受到影響。
編輯:
Map map = *(Map*)data;
復制map
結構(默認復制構造函數,我猜)所以從現在開始,如果源地圖更改副本將不會。
你應該繼續使用指針,如下所示: Map* pMap = (Map*)data;
並像這樣檢查指針: kill_this_thread = pMap->kill_chunk_loader_thread;
所以你從源地圖中讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.