同步2个posix线程

发布于 2024-10-20 11:11:16 字数 435 浏览 1 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄人书 2024-10-27 11:11:16

难道你不能这样做:

void *thread1(void* arg)
{
   // your code

   lock(&mutex);
   counter++;
   if (counter == 2) {
      // whatever
   }
   unlock(&mutex);
}

当然,假设计数器在任一线程启动之前初始化为 0。

Couldn't you just do:

void *thread1(void* arg)
{
   // your code

   lock(&mutex);
   counter++;
   if (counter == 2) {
      // whatever
   }
   unlock(&mutex);
}

assuming counter is initialized to 0 before either thread starts, of course.

看海 2024-10-27 11:11:16

顺便说一句,这里很好地使用了互斥锁。

您可以添加另一个由相同互斥锁保护的计数器,并且仅对其进行增量。然后在退出代码中,您可以检查它以确认所有线程都已启动。

即将其更改为“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文