MinGW and std::thread - c++

So I've been trying to get the following code to compile and run on Windows by using a MinGW compiler.
#include <iostream>
#include <thread>
void test()
{
std::cout << "test" << std::endl;
}
int main()
{
std::thread t(test);
}
I'm compiling with the following command:
g++ -std=c++11 test.cpp -o test.exe
Now the problem is the version of MinGW one should use and I've tried about all the versions I know of.
MinGW-builds: thread-win32
MinGW-builds: thread-posix
MinGW-w64: stdthread experimental rubenvb
MinGW-w64: stdthread experimental rubenvb 4.7
Number 1 doesn't work, since GCC apparently only supports pthread stuff internally.
Number 2 does compile and it essentially even outputs test (see the last line of the output), but it also crashes with the error:
terminate called without an active exception
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
test
Number 3 and 4 again do compile, but they don't output test and instead instantly crashes, but with a more descriptive output:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Google brought me of course to the GCC bug tracker and some other posts, that suggested to use -pthread, which doesn't help at all.
I've also tried manually linking against winpthread and pthread, but that doesn't do anything either.
There's also no difference between -std=c++11 and -std=gnu++11...
I'm really lost right now and don't know, if it's at all possible to get a MinGW version, that supports std::thread, but maybe I'm just overlooking some compiler flags. I hope someone out there can help me!

You forgot to join your thread:
t.join();

FYI, there is already a native win32 implementation of std::thread and sync primitives. It is a header-only library and works on any C++11 compliant version of MinGW.
https://github.com/meganz/mingw-std-threads

Related

C++ Threads not working, "error: 'thread' is not a member of 'std'"

I'm going to keep it fast and simple.
Here's the code I've written:
#include <iostream>
#include <thread>
void myFunc()
{
std::cout << "Hello!" << std::endl;
}
int main()
{
std::thread myThread(myFunc);
myThread.join();
return 0;
}
This is the command I've used to compile the program:
g++ threads.cc -o threads.exe -std=c++11
This is the error I'm getting:
threads.cc: In function 'int main()':
threads.cc:11:6: error: 'thread' is not a member of 'std'
std::thread myThread(myFunc);
^
threads.cc:13:6: error: 'myThread' was not declared in this scope
myThread.join();
^
I'm running Windows 10 and as you can see I'm trying to compile the program with GCC.
Can anyone help me with this? I've tried a few different ways to do multi-threading in C++, but none have worked.
The day after tomorrow I'll attend to a programming competition at my school and to make things go faster (the programs may only take up to 5 seconds to process data, which can be a lot) I'm thinking multi-threading could really help. You might think I should know this if I learn programming at school, but I haven't started that course yet and I'm just interested in the competition because it seems fun.
EDIT:
I have now installed the packages "mingw32-libpthreadgc" and "mingw32-libpthreadgce" (both the dev and dll classes). I also installed the "mingw32-pthreads-w32" (dev, doc and lic classes).
I have tried a few different includes <thread>, <pthread>, <pthread.h>. I have also tried adding the flag "-pthread" and "-lpthread". Also, I don't think we'll be allowed to use those flags anyways.
Nothing has worked so far.
I would be awesome if anyone could give a concrete example of which package / packages must be installed, which file / files to include and a short example code (in case mine won't work). We're not allowed to use any libraries except for the standard ones, but running a linux vm is probably fine, so any linux-only example works too.
I haven't found an example like that anywhere yet, so that would be awesome! Thanks!
(Yes, I did restart my computer)
When you install mingw sepect posix threads instead of default

g++ - Why do I have to pass "-pthread" option while using std::thread?

I'm just trying to understand a concept used by g++. Here my very simple std::thread application:
#include <iostream>
#include <thread>
void func() {
std::cout << "Running..." << std::endl;
}
int main()
{
std::thread t(func);
t.join();
return 0;
}
I'm able to compile it on macOs/Xcode 9.0 setup with following command:
g++ main.cpp -std=c++11
But I'm unable to compile it on Linux with the same command, as far as I know I have to pass -pthread option too. Otherwise it gives me following error:
gcc version 7.1.1 20170622 (Red Hat 7.1.1-3)
main.o: In function `std::thread::thread<void (&)()>(void (&)())':
/usr/include/c++/5/thread:137: undefined reference to `pthread_create'
I think it's illogical and I shouldn't even know that it's implementing the std::thread class via pthread. Why do I have to pass -pthread option and link against pthread library? Isn't C++11 supposed to abstract me away from platform specific details? Or do I have any other alternative libraries such as pthread that I can link against for my std::thread usage? Or should I report that as a bug?
Thanks.
According to GCC's concurrency page, it's necessary to provide additional options to the compiler based on the features being used. You can verify that your version of GCC's threads rely on POSIX threads:
$ gcc -v 2>&1 | grep "Thread model"
Thread model: posix
See this bug report for a justification for the behavior:
The problem is that not all targets need -pthread, or some which do need it spell it differently, and not all platforms define _REENTRANT when the option is used, so there's no reliable way to do what you're asking for.
I am moving pthread to std:thread in C++11 and have encountered the same phenomenon you've been met, and I found this artical -- it may be the proper answer: https://developers.redhat.com/articles/2021/12/17/why-glibc-234-removed-libpthread#
A quick conclusion: It depends on the version of glibc. glibc with versions prior to 2.34 will require the -lpthead flag even the code does not use pthread explicitly.
To check the version of glibc we can use ldd --version command, on my Ubuntu 20.04, it returns like this: ldd (Ubuntu GLIBC 2.31-0ubuntu9.9) 2.31, so I still have to add the -lpthread flag to use std:thread.
pthread is an industry standard over the OS specific threads, using the OS specific calls.
std::thread is an abstraction in C++ that could be implemented using pthread or the OS's native threads. But to make it work on as many OS's as possible fast the std-library implementer could just implement it in posix as they should be good to go on all compliant OS's.
There are exceptions, some windows only std-library uses windows native threads instead.

C++ 11 Threads, Error Pure virtual function called

here is a very minimal C++11 Thread API code that I am trying to compile
#include<iostream>
#include<thread>
using namespace std;
void threadFunction(void)
{
cout<<"hello from thread:";//<<this_thread::get_id()<<endl;
}
int main()
{
std::thread t(threadFunction);
t.join();
return 0;
}
On Compiling this as
g++ thread1.cpp -pthread -std=c++11
I get the following error
pure virtual method called
terminate called without an active exception
Aborted
What wrong, can someone please help
Note that I am compiling this on Beaglebone Black with ARM A8 processor
This is a bug in either libstdc++ or Clang, depending on who you ask. It should work if you are using a version of Clang released after October 2013. What do you see when you run g++ --version?
As a workaround, you could try using this command line instead. I don't guarantee that it would work; please post a comment with your results.
g++ -pthread -std=c++11 -D__GCC_HAVE_SYNC_COMPARE_AND_SWAP_{1,2,4} thread1.cpp
Here's the bug report:
http://llvm.org/bugs/show_bug.cgi?id=12730
And here's the official fix to the Clang driver:
https://llvm.org/viewvc/llvm-project?view=revision&revision=191707
I don't know if this was also previously a bug in the GCC driver, and/or whether it's been fixed.
Ran into the same problem on a Raspberry Pi 2 Model B with an ARM Cortex-A7.
Compiled with g++-4.7, turned out the culprit was a compiler flag:
-march=armv7-a
Although clang had a related issue, this is entirely a gcc bug now recorded at: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62100

C++11, GCC 4.8.1,Code::Blocks, threading, what a head ache

--EDIT
If you would like to use MinGW GCC 8.4.1 and threads/mutex/futures/atomics do not download the Win32 threader version insted download the Posix version.
--EDIT
My installation of MinGW is as follows:
x32-4.8.1-release-win32 (as the threader) - sjlj rev 5
I have unpacked and correctly confirmed that MinGW GCC 4.8.1 (revision 5) is installed in C:\MinGW\mingw32. I have set up Code Blocks to look for the latest and greatest compiler in the correct path (this I am sure of). I can compile a normal program using #include iostream. Ok now when I try and run a program using #include thread it gives me "error: 'thread' is not a member of 'std'".
Now here is what I have done and what I have tried:
I am following a sort of template or tutorial here at cplusplus.com.
I have the code exactly as it is presented on the webpage (towards the bottom).
I have tried, in Code Blocks, to use Compiler flags "Have g++ follow the C++11 ISO language standard -std=c++11".
I have also tried the flag "Have g++ follow the coming C++0x ISO language standard -std=c++0x"
I have tried both at the same time and one at a time, no mas.
I have also tried those commands manually.
Another command I tried manually was -std=gnu++11 which was recommended in the thread header.
--EDIT
It seems like __cplusplus is < 201103L which is stated (or rather defined) in the thread header.
This only happens when I manually use -std=c++11, for some reason C::B removes it if it was manually stated so I must use a check box to use this flag...
--EDIT
My compiler settings under the Toolchain Executables tab are as follows:
C compiler: i686-w64-mingw32-gcc-4.8.1.exe
C++ compiler: i686-w64-mingw32-c++.exe
Linker for dynamic: i686-w64-mingw32-c++.exe
Linker for static: ar.exe
Debbuger: GDB/CDB debugger: default
Resource compiler: windres.exe
Make Program: mingw32-make.exe
I have tried using other executables in the bin folder and still no luck...
I'm starting to wonder if GCC supports C++11 or threading !?
Has anyone been able to get threads to work with MinGW GCC, Code blocks or in general?
If so how did you do it? Any links that might help? Any advice?
P.S. I know there are other ways of threading like posix or other SDK's like SFML (I have successfully tried threading with this). But I want to use GCC threading and I'm quite baffled as to why it is so hard to do seeing as all the necessary files are there...
--EDIT
I have found that when I manually compile the program outside of Code Blocks I still get the same errors, whether I use g++ c++ or i686-w64-mingw32-g++/c++
here is the command I run to build the files:
C:\MinGW\mingw32\bin>g++.exe -D__GXX_EXPERIMENTAL_CXX0X__ -o0 -g3
-Wall -c -fmes sage-length=0 -std=c++11 -Wc++11-compat -o obj\Debug\main.o "F:\C Projects\Code Blocks\thread\main.cpp"
still returns error: 'thread' is not a member of 'std'
Could this be a bad build? I will try other revisions...
--EDIT
probably to late for an answere, but here is what worked for me:
1. Get x86_64-w64-mingw32-gcc-4.8-stdthread-win64_rubenvb.7z from:
http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.8-experimental-stdthread/
2. Setup a new compiler in codeblocks with
x86_64-w64-mingw32-gcc-4.8.1.exe
x86_64-w64-mingw32-g++.exe
x86_64-w64-mingw32-g++.exe
ar.exe
windres.exe
mingw32-make.exe
3. Set the new compiler for your project
Right click in your project -> build options
Select the new compiler
Under compiler falgs check -std=c++0x and -std=c++11
Under Other options set -std=gnu++11
4. Have fun with c++11 concurrency
Hope that works for you also, as an alternative you can just use visual studio.
I think you meant GCC 4.8.1 - the answer is yes, it supports a set of C++11 features including partial multi-threading support. Please visit http://gcc.gnu.org/releases.html to see supported set.
gcc 4.8.1 is C++11 feature complete. I cannot speak to the Windows implementation but certainly on Linux and OS X it works as advertised, including all the concurrency functionality. I just #include <thread> and call g++ -std=gnu++11 and it works. Here's a minimal piece of code that compiles just fine:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mx;
int i;
void thrfunc();
int main(void)
{
i=0;
std::thread thr1(thrfunc),thr2(thrfunc);
thr1.join();
thr2.join();
return 0;
}
void thrfunc()
{
mx.lock();
i++;
std::cout << std::this_thread::get_id() << " i: " << i << std::endl;
mx.unlock();
}
I had the same issues, I installed the lates MinGW-Builds
http://sourceforge.net/projects/mingwbuilds/files/mingw-builds-install/
and set my toolchain executables to:
x86_64-w64-mingw32-gcc-4.8.1.exe
x86_64-w64-mingw32-g++.exe
x86_64-w64-mingw32-g++.exe
ar.exe
windres.exe
mingw32-make.exe
I hope this helps.

C++ runtime errors in CodeBlocks when printing strings with cout <<

I recently started using CodeBlocks and began encountering odd runtime errors which I have traced back to printing strings using cout <<. For example, even the following..
#include <string>
#include <iostream>
int main()
{
std::string str;
str = "Hi!";
std::cout << str << std::endl;
return 0;
}
results in an error. It will compile fine (using Borland) but when I run it I get a pop up window saying 'test.exe has stopped working' and in the console I get the message:
Process returned -1073741819 (0xC0000005) execution time : 1.526 s
Press any key to continue.
It compiles and runs fine in MS Visual C++ and with G++ in Ubuntu.. any thoughts would be greatly appreciated!
Cheers,
Weatherwax
My one-off comment ended up helping solve the problem so here it is packaged up as an answer for future users:
This guy had a similar issue and it ended up being a linker issue which he
fixed. The fix is the last post in the thread, although reading the
whole thread could be useful for you.
Long Story short: Borland compiler is a bit dated and annoying to use. Ended up being a linker issue within borland. Better off using a different compiler like GCC/G++ or Visual Studio compiler.
This answer is here to elaborate on the root cause of the issue.
The reason for your crashing program is because the wrong runtime library is being linked. Specifically, your example is compiled as a single threaded object file(the default) but the linking step is using the multithreaded cw32mt.lib runtime -- the "mt" suffix at the end means multithreaded.
The solution is to make sure the runtime your program is compiled to use matches with the runtime you're linking against. A few ways to do this.
Important bcc32 compile switches:
-tW Windows GUI program. WinMain() is expected
-tWC Windows Console program. main() is expected. default.
-tWR Use dynamically linked runtime. Absence implies static runtime linkage.
-tWM Use multithreaded runtime. Absence implies single thread.
Compiling your example program as single threaded like this works:
bcc32 -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32.lib import32.lib,,
or you can compile it as multithreaded like this(note the -tWM switch matching up with cw32mt.lib):
bcc32 -tWM -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32mt.lib import32.lib,,
A third approach that is easier and less error prone is to not call the linker yourself. Instead, let the compiler drive the linker indirectly(similar to gcc):
bcc32 -tWM -oexample.obj -c example.cpp
bcc32 -tWM example.obj -eexample.exe
For your simple example, it can even be shortened to:
bcc32 -eexample.exe example.cpp
Lastly, you can pass the -tW switch multiple times. For example, this command compiles your example as a console program with multithread support and dynamic runtime linkage:
bcc32 -tWM -tWR -tWC -eexample.exe example.cpp
The produced example.exe executable is much smaller and its import table has an entry for CC3250MT.DLL confirming that the borland runtime is dynamically linked.
We should not assume that a non-functioning program is caused by nonconformity to the standard or a bug in the tool we're using without first investigating user error as a potential cause (even though in this case it's tempting to do so). In the OP's case, the code::block IDE didn't have the right commands setup for the toolchain being used.