在学习多线程的过程中,我创建了两个互斥锁分别对应标准输入、输出流,创建了两个线程。
具体代码如下:
#include <bits/stdc++.h>
#include <conio.h>
// #include <windows.h>
using namespace std;
int main(void)
{
bool finished[2] = {false};
mutex lock_stdout = mutex(), lock_stdin = mutex();
thread t[2] =
{thread([&finished, &lock_stdin, &lock_stdout]() -> void
{
unsigned long long int ull = 0ULL;
lock_stdin.lock();
while (!kbhit())
{
lock_stdin.unlock();
lock_stdout.lock();
cout << "t[0] : " << (ull++) << endl;
lock_stdout.unlock();
// Sleep(50);
lock_stdin.lock();
}
lock_stdin.unlock();
lock_stdout.unlock();
finished[0] = true;
}),
thread([&finished, &lock_stdin, &lock_stdout]() -> void
{
unsigned long long int ull = 0ULL;
lock_stdin.lock();
while (!kbhit())
{
lock_stdin.unlock();
lock_stdout.lock();
cout << "t[1] : " << (ull++) << endl;
lock_stdout.unlock();
// Sleep(50);
lock_stdin.lock();
}
lock_stdin.unlock();
lock_stdout.unlock();
finished[1] = true;
})};
t[0].detach();
t[1].detach();
cout << "All threads have finished running." << endl;
return 0;
}
在代码第10行,我显式调用了mutex类构造函数来创建互斥锁对象,即
mutex lock_stdout = mutex(), lock_stdin = mutex();
在Win7下使用MinGW64编译,编译器报错如下:
test.cpp: In function 'int main()':
test.cpp:10:28: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
mutex lock_stdout = mutex(), lock_stdin = mutex();
^
In file included from D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/condition_variable:39,
from D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/x86_64-w64-mingw32/bits/stdc++.h:103,
from test.cpp:1:
D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
^~~~~
test.cpp:10:50: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
mutex lock_stdout = mutex(), lock_stdin = mutex();
^
In file included from D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/condition_variable:39,
from D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/x86_64-w64-mingw32/bits/stdc++.h:103,
from test.cpp:1:
D:/MinGW64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
^~~~~
显然我调用的并非复制构造函数mutex(const mutex &),但编译器却提示我是因为使用了mutex(const mutex &)才报错的。而一旦我直接隐式调用构造函数,即直接写成
mutex lock_stdout, lock_stdin;
形式,所有问题就都解决了。
小生有点强迫症,喜欢显式调用构造函数来创建对象,奈何见识浅薄,不得其原因,敢问各位这是为什么?如何解决?