How do I compile a cpp file with the thread class? [duplicate] - c++

This question already has an answer here:
Does MinGW-w64 support std::thread out of the box when using the Win32 threading model?
(1 answer)
Closed 4 years ago.
I am learning to use threading so I am trying to run code utilizing the thread class so that I can run functions concurrently. However, trying to compile it in the terminals terminal, it says that thread and its object t1 is not declared.
threading.cpp:16:5: error: 'thread' was not declared in this scope
thread t1(task1, "Hello");
^~~~~~
threading.cpp:21:5: error: 't1' was not declared in this scope
t1.join();
I thought g++ doesn't support it but I also include in its argument to support c++11
g++ -std=c++11 threading.cpp
Any idea what I should I do about this error?
(OS: windows, gcc version 6.3.0)
Code is provided below(an example from a website):
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}

Any idea what I should I do about this error?
Your code compiles and runs fine with a recent version of GCC (coliru.com). And the same is true for older versions (e.g. GCC 6) and with -std=c++11. Your problem must be elsewhere:
Perhaps you're using an extremely old compiler?
Perhaps your C++ standard library headers are not installed?
Perhaps your C++ standard library headers are located someplace unexpected? That could happen if you're using a custom-installed version of the compiler or standard library.

Related

Can't resolve namespace member 'thread'

I wanted to practice with standard C++ threads instead of UNIX ones, but soon encountered a problem, whenever I write std::thread CLion underlines it with red and says Can't resolve namespace member 'thread'. I checked my CMake file it's set for C++11. I reinstalled the latest version of MinGW (6.3.0) and ticked a box with G++ compiler. I have been told by my friend that he uses Cygwin and everything works. But is it still possible to make it work with MinGW?
#include <iostream>
#include <thread>
#define BUFFER_SIZE 3
#define PROD_NUM 3
#define CONS_NUM 2
void produce(){
//production
}
void consume(){
//consumption
}
int main() {
std::cout << "Hello, World!" << std::endl;
int i,j;
std::thread producer(produce);
std::thread consumer (consume);
return 0;
}
The code itself has literally nothing
EDIT
in thread library there is
#pragma GCC system_header
#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else
#include <chrono>
#include <functional>
#include <memory>
#include <cerrno>
#include <bits/functexcept.h>
#include <bits/functional_hash.h>
#include <bits/gthr.h>
#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/**
* #defgroup threads Threads
* #ingroup concurrency
*
* Classes for thread support.
* #{
*/
/// thread
class thread
{
public:
// Abstract base class for types that wrap arbitrary functors to be
// invoked in the new thread of execution.
struct _State
{
virtual ~_State();
virtual void _M_run() = 0;
};
can you make sure if the library is available in the CLion toolchain? For example Cygwin does have the include.
CLion shows things red when it can't link codes with the library.
It is possibly a host environment variable error. Make sure your CMakeLists.txt is working and your environment variables, standard library linkage is correct as well as your compiler setup.
Compiler version and and standard libraries compatible. (e.g. you are using a cross-compiler (RasPi, Android) but environment vars shows host library etc. will make it fail)
Check this relevant post, it may help.
C++11 std::threads vs posix threads
Ok, so I finally solved the problem. I installed Cygwin and in CLion Settings I manually linked C/C++ compilers (for some reason CLion was unable to auto-detect them). Cleared all and re-indexed the project. Now it shows no errors and code compiles.
Regarding MinGW, I read on cplusplus.com some posts regarding the issue but they were about previous versions of MinGW and it was said that they finally fixed it, however I tell: No, they didn't. Here there is a nice repository and its README file suggests that thread of win32 rely on gthreads, however i found gthread file in my libraries everything seemed ok... so still need to investigate the issue. Write your ideas and experience here if you know more.
As for now solution is Cygwin, use it instead of MinGW.
P.S. Thanks #KillzoneKid for links

libstdc++ cannot find thread file on Mac

Please take a look at this simple C++ program:
#include <iostream>
#include <thread>
void thread_test()
{
std::cout << "Thread test\n";
}
int main(int argc, const char * argv[])
{
std::thread t(thread_test);
t.join();
return 0;
}
I'm trying to compile it with Xcode on macOS Sierra. And it does not compile. It says 'thread' file not found.
In the build settings I'm using libstdc++ (GNU C++ standard library) option for C++ Standard Library. If I switch this setting to libc++ (LLVM C++ standard library with C++11 support) then it's ok, it compiles. But my goal is to compile it somehow by using libstdc++, not libc++. Is it even possible? Can you give me a piece of advice, please?
The version of libstdc++ shipped with Xcode is very old, and it doesn't not include thread. pthreads on macOS is missing some functions with timeouts (e.g. pthread_mutex_timedlock()).
You simply can't use std::thread and Xcode's supplied libstdc++ on macOS together. Either you must switch to libc++ or use a different library boost::thread does work. TinyThread++ is also an alternative that will work under macOS with libstdc++.

C++ how to sleep?

I am a novice in C++ and I am struggling to make my program to wait a few minutes before executing a function.
I know there are lots of topics about it but I have a problem with my compiler. I can't seem to use the boost library nor the thread library. And since I can't use the thread library, I can't use the chrono library either.
I am using GNU GCC Compiler. I have MinGW installed. Is it outdated or something? What is the best compiler to code in C++?
My OS is Windows.
You could use this
#include <unistd.h>
...
usleep(1000); // Time in microseconds
or
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main(){
int sleepTime = 1000;
Sleep(sleepTime);
return 0;
}
<thread> is only available starting with C++11.
It's likely you don't have the proper flags to tell GCC you want to enable C++11 support, which is disabled by default.
The command line parameter is -std=c++11.
Then, you can use std::this_thread::sleep_for() for cause your program to fall asleep. Note that if you only have one thread in your program, it will probably stop responding to user actions during that time.

How do I setup my g++ compiler for C++11? [duplicate]

This question already has answers here:
Closed 10 years ago.
I tried a basic program:
// ThreadExample.cpp
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
thread t1(task1, "Hello");
t1.join();
}
One I actually found on stackoverflow, but I tried compiling it using:
g++ -std=c++0x -pthread ThreadExample.cpp -o ThreadExample -lm
However, I keep getting an error that thread is undeclared. I have version 4.7.1 of the MinGW GNU for Windows. Is there something I can change so I can use C++11?
Noone has contributed an implementation of <thread>, <mutex> etc for Mingw yet, except when using Mingw with (optional) Pthreads support via a third-party pthreads implementation.
I started a thread at http://gcc.gnu.org/ml/libstdc++/2012-05/msg00020.html with some suggestions for implementing the missing features in terms of Windows native threads, but as I don't have a Windows machine and noone else has volunteered to do anything, nothing happened. I have almost zero interest in implementing it myself, because I never develop for Windows so it would be of no use to me whatsoever, and I would rather spend my limited free time implementing things I will actually use. If anyone wants to work on it I'd happily advise them and review their code and help shepherd it into GCC.

Starting a std::thread with static linking causes segmentation fault

To learn c++11 (and boost) I am writing a simple http-server using boost asio and c++11 (for threading and lambdas).
I want to test the new c++11 lambdas and std::thread so I tried to start the io_service.run() like this in a std::thread with a lambda:
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using std::cout;
using std::endl;
using boost::asio::ip::tcp;
class HttpServer
{
public:
HttpServer(std::size_t thread_pool_size)
: io_service_(),
endpoint_(boost::asio::ip::tcp::v4(), 8000),
acceptor_(io_service_, endpoint_)
{ }
void Start() {
acceptor_.listen();
cout << "Adr before " << &io_service_ << endl;
std::thread io_thread([this](){
cout << "Adr inside " << &io_service_ << endl;
io_service_.run();
});
io_thread.join();
}
private:
boost::asio::io_service io_service_;
tcp::endpoint endpoint_;
tcp::acceptor acceptor_;
};
int main() {
HttpServer server(2);
server.Start();
}
This terminates with segmentation fault. Additionally sometimes it is running the cout inside the lambda, sometimes not (although endl should flush). In any case, it prints the correct address of io_service_. However, when I replace the std::thread with a boost::thread (no other change!), everything is working fine.
I would appreciate it if anyone has an idea where the problem is caused (could be asio, std::thread or std::lambda).
Additional information:
According to another post accessing the member io_service_ within a lambda is fine when capturing this, as I do it.
I am running gcc 4.6.1 on Ubuntu and boost 1.46. G++ parameters:
g++ -std=c++0x -static -I/home/andre/DEV/boost_1_48_0/include/ -L/home/andre/DEV/boost_1_48_0/lib/ -o webserver main.cpp -lboost_system -lboost_thread -lpthread
Update:
Removing -static fixed the problem. I found out that the problem has nothing to do with boost or lambdas and can be reproduced whenever building static and using std::thread. For any reason this combination does not work.
I think this post describes almost the same, however I don't really understand the details and the error message is different.
So I wonder why std::thread and static linking don't seem to work together. Is there a reason why static linking is not allowed here? I updated the question title and removed the boost tag.
Link your app with -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
More here https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590
It works for me.
Removing -static solved the problem. I found out that it has nothing to do with boost or lambdas, but with static linking and std::thread, which don't seem to work together for any unknown reason (see also this post that might be related).
I guess the question why they don't work together is - though interesting - out of scope for now, and I am glad with the answer, so this can be marked as answered.