我有一个C ++程序,它运行一堆线程来操作相同的数据。这些线程中的每一个都有一个指向正在被操纵的对象的指针,例如:
thread1和thread2都有一个指向object1的指针 object1-> addSomething()可以由thread1或2使用并引用同一个对象
现在,如果两个线程同时完成这些操作可能会给它们带来麻烦,所以我想要一个简单的阻塞机制。我想要的只是这个:
void method()
{
waitUntilFree()
blockForOthers()
doSomething()
unblock()
}
有一种简单的方法吗?我只是想阻止并等到它是免费的。我不介意线程可能需要等待一段时间。有一个简单的机制来做到这一点?我使用Boost作为这些线程,但我不能为我的生活找到一种方法来做这个(似乎)简单的块等待事情。
答案 0 :(得分:5)
如Ferruccio所述,您可以使用同一个库中的Mutex Boost.Mutex
进行同步:
class X {
boost::mutex m_mutex;
public:
void method() {
boost::mutex::scoped_lock lock(m_mutex);
// ... now locked, do stuff
} // mutex automatically unlocked when scoped_lock is destructed
};
答案 1 :(得分:2)
由于您已经在使用Boost,因此可以使用Boost mutex来保护多个线程的同时访问。
然后在每个线程上使用join()等待它完成。
// create the mutex where it can be accessed by all threads
boost::mutex lock;
// in each thread
lock.lock();
// do something with shared data
lock.unlock();
// for each thread
thread.join(); // wait for thread to finish
答案 2 :(得分:1)
使用互斥。
您可以在http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SYNCHRONIZATION
找到有关它的更多信息#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute functionC */
if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}
if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
答案 3 :(得分:0)
您正在寻找所谓的互斥体。这些作为线程库的一部分。看看this dr. dobbs article。