0

why is this happen?

source code: #include <iostream> #include <thread> using namespace std; void cthread(){ cout<<"this method's call by thread"; } void number(int n){ cout<<n<<endl; } int main() { thread t (cthread); thread t2 (&number,1); t.join(); t2.join(); return 0; } in code-blocks gnu gcc , i've got an error message "use of undeclare thead". in sololearn it's work perfectly in

4th Feb 2019, 10:07 AM
sherlockholmes
sherlockholmes - avatar
3 Respuestas
+ 6
The problem is that gcc only has an implementation for POSIX threads. These threads only work on linux environments, which is what sololearn runs on, so it works there¹. Windows, however, does not use POSIX threads and gcc has no implementation for that. Gcc detects that and pretty much comments out the whole thread class, which results in the "use of undeclare thread" error. There are some specific versions of gcc where they did have an implementation for windows but those are quite old and I don't really know them at the top of my head. If you want to use threads on windows you can either use the windows api: https://docs.microsoft.com/en-us/windows/desktop/procthread/creating-threads but that won't be portable. Or you can use the compiler from visual studio, which does have a working implementation for windows threads and I believe clang also has a working implementation. ¹Edit: Appearently sololearn doesn't run on linux, my bad. My guess is that it uses a build that has --enable-threads=posix instead of win32, you can check with "g++ -v" in the command prompt. Bottom line is gcc doesn't play well with threads. :)
4th Feb 2019, 10:29 AM
Dennis
Dennis - avatar
+ 2
Hmm, not sure why I thought it runs under linux. #include <iostream> int main() { #if defined( _WIN32 ) std::cout << "Windows\n"; #elif defined( __unix__ ) std::cout << "Linux\n"; #endif } Indeed prints windows... I figured it because his program runs under my linux but not under windows and I read up on this before which explained the same stuff.
4th Feb 2019, 12:01 PM
Dennis
Dennis - avatar
+ 2
It compiles on my linux when I do g++ file.cpp in the command line without the linking. But then again I'm using cygwin, not sure if it matters. :)
4th Feb 2019, 12:05 PM
Dennis
Dennis - avatar