同步2个posix线程
我有 2 个线程,它们都在最后删除了两者都需要的内存。我的问题是,也许一个线程可能会在另一个线程开始之前开始和结束,因此它会删除另一个线程所需的内存。我怎样才能同步它们以免发生这种情况。
作为设计,我的线程如下所示:
void* thread1(void* arg)
{
lock(&mutex);
counter++;
unlock(&mutex);
// more code here
lock(&mutex);
counter--;
if(counter == 0)
{
delete a;
delete b;
}
unlock(&mutex);
}
另一个线程看起来相同,但这并不是在线程 2 启动之前停止线程 1 完成。
谢谢。
I have 2 threads and both of them are deleting memory at the end nedded by both. My problem is that maybe it can happen that a thread start and finish before the other one starts and so it deletes the memory nedded by the other thread. How can I synchronize them so that this can't happend.
As a design my threads look like this:
void* thread1(void* arg)
{
lock(&mutex);
counter++;
unlock(&mutex);
// more code here
lock(&mutex);
counter--;
if(counter == 0)
{
delete a;
delete b;
}
unlock(&mutex);
}
The other thread looks the same, but this isn't unoff to stop thread1 to finish before thread2 starts.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
难道你不能这样做:
当然,假设计数器在任一线程启动之前初始化为 0。
Couldn't you just do:
assuming counter is initialized to 0 before either thread starts, of course.
顺便说一句,这里很好地使用了互斥锁。
您可以添加另一个由相同互斥锁保护的计数器,并且仅对其进行增量。然后在退出代码中,您可以检查它以确认所有线程都已启动。
即将其更改为“if (counter == 0 &&started == 2)”。
既然你正在保护counter &开始使用互斥锁进行访问,如果 1 & 2 个进程都在任一完成之前启动,第一个完成的将看到started = 2 且counter = 1。另一个将看到started = 2 且counter = 0 并删除资源。
如果一个线程在另一个线程启动之前运行完成,它将看到started = 1和counter = 0。然后另一个线程将看到started = 2和counter = 0并进行清理。
Good use of the mutex here, BTW.
You could add another counter, protected by the same mutex, and only do the increment on it. Then in the exit code you could check it to confirm that all the threads got to start.
i.e. change it to "if (counter == 0 && started == 2)".
Since you are protecting counter & started access with a mutex, if 1 & 2 both start before either finishes, the first to finish will see started = 2 and counter = 1. The other will see started = 2 and counter = 0 and delete the resources.
If a thread runs to completion before the other starts, it will see started = 1 and counter = 0. Then the other thread will see started = 2 and counter = 0 and clean up.