同时启动 pthreads
确保一堆 pthreads
同时启动的不同方法有哪些?
我只能找到一种方法,即。在主线程中初始化一个屏障,然后在新创建的 pthread 中等待它。
What are the different ways of ensuring that a bunch of pthreads
all start at the same time?
I could find only one way, ie. initializing a barrier
in the main thread, then waiting on it in the newly created pthreads.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这几乎就是我过去的做法。完全。
请注意,这实际上并不能保证所有线程在第一个线程开始执行某些操作之前都已启动,只是主线程已创建它们。
为此,您可以使用类似于以下方法的方法:
无论线程必须执行什么初始化操作才能被视为已启动,都将在
claim
和subtract
之间发生。从进一步的调查中我发现,障碍实际上是一种更优雅的方法。它们实际上在我使用的 pthread 实现中不可用,这就是为什么我的代码可能看起来有点冗长。
但是,我会保留原样,以防有人使用 v6 之前的 pthreads 或不同的线程方法(没有障碍),并且因为,正如所提出的问题,这是一个不同的这样做的方法。
That's pretty much exactly how I've done it in the past.
Note that this doesn't actually guarantee that all the threads have started before the first one starts doing something, just that the main thread has created them.
In order to do that, you can use something like the following method:
Whatever initialisation a thread has to do to be considered started will occur between the
claim
and thesubtract
.I see from further investigation that barriers are actually a more elegant way to do this. They weren't actually available in the pthread implementations I used which is why my code may seem a little verbose.
However, I'll leave it as-is on the off-chance that someone uses pre-v6 pthreads or a different threading method (without barriers) and because, as the question asked, this is a different way of doing it.
您可以使用
pthread_cond_broadcast
。由于互斥体的原因,它们不会完全同时启动。您可以尝试为每个线程使用不同的互斥体,但对同一条件变量使用不同的互斥体是未定义的。You can use
pthread_cond_broadcast
. They won't be launched completely simultaneously because of the mutex. You could try to use a different mutex for each thread, but using different mutexes for the same condition variable is undefined.