如何使用互斥锁锁定对布尔值的访问?



>solved!:im 在新线程中复制 Map 的实例,并且不使用引用。

我正在学习如何使用多个线程。对于这个im编程一个小游戏,我希望游戏在主线程中运行,关卡的下一个块应该加载到另一个线程中。为此,我在向量周围设置了一个互斥锁,以告诉加载线程接下来要加载什么。在这个互斥锁中,我还有一个布尔值来告诉线程 tu 何时终止。

在 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: %dn", map.kill_chunk_loader_thread);
kill_this_thread = map.kill_chunk_loader_thread;
printf("4-kill_chunk_loader_thread: %dn", 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 ordern");
}
else
{
printf("in thread waiting for ordern");
SDL_CondWait(map.can_process_order, map.pending_orders_mutex);
}
}
SDL_UnlockMutex(map.pending_orders_mutex);          // unlock mutex
//load actual order
}
printf("thread got killedn");
return 0;
}

杀死线程(主线程(

SDL_LockMutex(pending_orders_mutex);            // lock mutex
printf("setting kill commandn");
printf("1-kill_chunk_loader_thread: %dn", kill_chunk_loader_thread);
kill_chunk_loader_thread = true;                // send kill command
printf("2-kill_chunk_loader_thread: %dn", 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

为什么主线程不更改加载线程中的"kill_chunk_loader_thread"布尔值?

首先,您应该尝试在问题中上传一个最小的完整程序。

看起来你设置了kill_chunk_loader_thread = true

但你没有设置map.kill_chunk_loader_thread = true

声明map部分与您的问题无关,但我想您没有使用对局部或全局变量的引用,或者您只是执行结构复制,因此当您更改一个结构时,另一个结构根本不会受到影响。

编辑:

Map map = *(Map*)data;复制map结构(我猜是默认复制构造函数(,所以从现在开始,如果源映射更改,则复制不会。

你应该继续使用指针,像这样:Map* pMap = (Map*)data;并像这样检查指针:kill_this_thread = pMap->kill_chunk_loader_thread;以便您从源地图中读取。

最新更新