【发布时间】:2018-03-07 15:23:39
【问题描述】:
我正在尝试使用互斥锁来避免多次写入 C/Cpp 中的同一线程。下面是我的程序流程。我对在哪里包含我的锁定和解锁代码感到困惑。
main() {
spawn a worker thread
}
worker_thread() {
read the input file name
read some content
write the content to the given file name
}
我看到的大多数实现,似乎都有这样的东西:
main() {
pthread_mutex_init(&myMutex;,0);
*spawn a worker thread*
pthread_join(thread1, 0);
pthread_mutex_destroy(&myMutex;);
}
worker_thread() {
read the input file name
read some content
write the content to the given file name
}
我想要的是这样的:
main() {
spawn a worker thread
}
worker_thread() {
read the input file name
read some content
pthread_mutex_init(&myMutex;,0) --> for the given file?
write the content to the given file name
pthread_mutex_destroy(&myMutex;);
}
非常感谢任何想法。谢谢!
【问题讨论】:
-
你使用的是c还是c++?如果您使用 c++11 及更高版本,请不要使用 pthread_mutex 而是使用 std::mutex
-
您是否试图防止在两个不同的线程中写入同一个文件?
-
您需要决定要保护哪些对象免受哪些线程或代码路径的并发访问。如果您只在一个线程中创建和使用了某些东西,那么除非您主动与另一个线程共享它,否则无需保护对该对象的访问。
-
为什么您试图阻止同时写入您的文件?根据您的操作系统,there are ways to do atomic write operations to a file without locking at the application level。
-
是的,我正在尝试防止不同线程同时写入同一个文件。
标签: c++ c multithreading synchronization mutex