I'm trying to implement a threaded object like this:
#include <pthread.h>
#include <iostream>
class Thread
{
private:
int id;
static void * run(void * arg)
{
int tid = (int)arg;
std::cout << "Thread " << tid << " executed." <<std::endl;
pthread_exit(NULL);
}
public:
Thread(int _id);
void start();
int get_id();
};
Here's the implementation of the public methods & constructor:
#include "std_thread.h"
Thread::Thread(int _id)
{
id = _id;
}
void Thread::start()
{
std::cout << "Thread created." <<std::endl;
pthread_t thread;
int rc = pthread_create(&thread, NULL, run, (void*)id);
if(rc)
std::cout << "Return code from thread is " << rc;
}
int Thread::get_id()
{
return id;
}
And here's main:
#include "std_thread.h"
int main()
{
Thread *thd = new Thread(0);
thd->start();
return 0;
}
When I create the thread object and call its start method, which is in turn supposed to print "Thread created." and run the thread body - it doesn't; actually, it does print Thread created to console, but doesn't seem to create a thread, or the thread just doesn't do anything. Everything compiles fine by the way, and there no run time errors.
Any ideas?
Your main returns before the thread gets a chance to run.
The program doesn't wait until all threads are done before exiting - once main is over, it's over, and the process is just shut down.
Have your pthread_t thread; as a member instead of a local variable, and add a method to wait for the thread to finish.
This is the simplest example I can come up with:
void Thread::wait()
{
pthread_join(thread, NULL);
}
int main()
{
Thread thd(0); // There's no point in using dynamic allocation here.
thd.start();
thd.wait();
return 0;
}
Related
I am new to threading, and i am trying to write a function that keep outputing an variable while i should be able to change that variable at runtime, and the output should change to my input once I input a new value in. By the following program is not running as i expected, whats wrong here? is there anything i can reference to so i can build this funciton out?
int a;
void* ptr;
void* Input(void* arg){
while(true){
std::cin >> a;
std::cout << std::endl;
}
return ptr;
}
void* Output(void *arg){
while(true){
std::cout << a << std::endl;
}
return ptr;
}
int main(){
pthread_t GetInput;
pthread_create(&GetInput,NULL,Input,NULL);
pthread_t GetOutput;
pthread_create(&GetOutput,NULL,Output,NULL);
}
Your main thread is not waiting for your child thread and exited when main() returned. To make your main thread to wait for children finish their jobs, you should call pthread_join() for them.
int main(){
pthread_t GetInput;
pthread_create(&GetInput,NULL,Input,NULL);
pthread_t GetOutput;
pthread_create(&GetOutput,NULL,Output,NULL);
pthread_join(GetInput, NULL);
pthread_join(GetOutput, NULL);
return 0;
}
Here's another alternative using std::async() for your code.
#include <chrono>
#include <future>
#include <iostream>
#include <mutex>
int a;
std::mutex mtx_;
void Input(void* arg) {
while (true) {
int tmp_a;
std::cin >> tmp_a;
{
std::lock_guard<std::mutex> lock(mtx_);
a = tmp_a;
}
std::cout << std::endl;
}
}
void Output(void* arg) {
while (true) {
{
std::lock_guard<std::mutex> lock(mtx_);
std::cout << a << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
auto ft_in = std::async(std::launch::async, Input, &a);
auto ft_out = std::async(std::launch::async, Output, &a);
ft_in.wait();
ft_out.wait();
return 0;
}
Well,I don't know how to use pthread.
And it seems Mr.john-park or Ms.john-park already gave a answer.
But I think use thread is a better choice.
To use it,we should:
#include<thread>
After that,if u want to start a new thread,and "connect" it with a function(In fact,we usually do)
There is a class named thread.
First,we should
thread *thread name*(*function name*);
WARNING:function nameshould be without "(" and ")"
May because here should be a pointer.
Then,to the question.
Suppose we wrote:
thread GetInput(Input);
thread GetOutput(Output);
When u want to stop GetOutput some time and run GetInput,
just
GetInput.join()
Here's a not so good example:
#include <iostream>
#include <thread>
using namespace std;
void f1()
{
while (true)
{
cout << "THREAD 1!" << endl;
}
}
void f2()
{
for (int i = 0; i < 10; i++)
cout << "THREAD 2!" << endl;
thread t1(f1);
t1.join();
for (int i = 0; i < 10; i++)
cout << "THREAD 2!" << endl;
}
int main()
{
thread t2(f2);
return 0;
}
First,we started t2.
Then t2 started t1.
Now we can know why we use join().
If we don't join(),
It'll be hard for us to read the output because it'll close the cmd window quickly.
But we can know,
after t2 end,
return 0;
ran.
But if we used join()
Here's the output:
THREAD 2!
THREAD 2!
THREAD 2!
...(THREAD 2!*10)
THREAD 1!
THREAD 1!
...(Always THREAD 1!)
This is my code:
void* task1(void* unused)
{
try {
cout << "Run Thread" << endl;
}catch (const char* msg) {
cout << msg << endl;
}
}
int main(int argc, char *argv[])
{
try {
pthread_t thread_id;
int res = pthread_create(&thread_id, NULL, &task1, NULL);
cout << res << std::endl;
exit(EXIT_SUCCESS);
}catch (const char* msg) {
cout << msg << endl;
}
}
In Ubuntu Code RUN.
In CentOS Code NOT RUN, if my use pthread_join(thread_id, NULL); code is run but can waiting pthread complete. I try pthread_tryjoin_np but code not run.
Please help me run code in centos is no wating
If the program main() exits before the thread actually starts (and runs to the point cout << ...), the thread will be terminated and not continue to run.
I.e. you need to wait with pthread_join() before the main() exits.
The case in Ubuntu is a pure coincidence, that the thread manages to print the line before it is terminated by the C++ runtime after the main() exits.
If you do not want to wait because you want to start multiple threads, you can use thread pool (array of threads). First you start all of them, and then you pthread_join() wait for all of them to finish.
Also, if the pthread_join() blocks although the thread terminated, make sure you created the thread as joinable. That is the default, so make sure that you do not explicitly set the thread attributes to PTHREAD_CREATE_DETACHED.
To be absolutely sure, you can provide thread create attributes explicitly and ensure that the thread is created as joinable:
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread_id, &attr, &task1, NULL);
pthread_attr_destroy(&attr);
pthread_join(thread_id, NULL);
(error handling not included)
Why you do not use C ++ 11? Standard library (STL) have the opportunity to develop crossplatform applications with threads. You can test on cpp.sh
#include <iostream>
#include <thread>
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
}
int main()
{
std::thread thr(task1,1);
thr.join();
return 0;
}
OR
#include <iostream>
#include <thread>
#include <chrono>
bool bThread = false;
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
bThread = true;
}
int main()
{
std::thread thr(task1,1);
try
{
thr.detach();
while (!bThread) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
catch(...) { return 1; }
return 0;
}
I am beginning to use the thread class.
In the main() thread below, an Example class is created.
Inside the constructor of Example, two threads are created in the Example::start() function.
Example::foo() is designed to print a message every second.
Example::bar() is designed to print a message every 5 seconds.
Inside the main() function, a loop is designed to print every 3 seconds.
I decided to not use join() in Example::start() because I would like to have the main() function continuously run.
Why does the main thread crash during run-time?
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono> // std::chrono::seconds
using namespace std;
class Example
{
public:
Example();
void start();
void foo();
void bar(int x);
};
Example::Example()
{
start();
}
void Example::start()
{
std::thread first (&Example::foo, this); // spawn new thread that calls foo()
std::thread second (&Example::bar, this, 5); // spawn new thread that calls bar(0)
// synchronize threads:
//first.join(); // pauses until first finishes
//second.join(); // pauses until second finishes
}
void Example::foo()
{
cout << "entered foo()" << endl;
int count = 0;
while(1) {
std::this_thread::sleep_for (std::chrono::seconds(1));
++count;
cout << "foo() count = " << count << endl;
}
}
void Example::bar(int x)
{
cout << "entered bar() x = " << x << endl;
int count = 0;
while(1) {
std::this_thread::sleep_for (std::chrono::seconds(5));
++count;
cout << "bar() count = " << count << endl;
}
}
int main() {
Example* c = new Example();
cout << "Example() created" << endl;
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(3));
cout << "main() thread loop..." << endl;
}
std::cout << "end of main()";
delete c;
return 0;
}
Foo::Start() initalizes two threads, thread Foo and thread bar. When the function Start returns to the main thread, the two thread objects go out of scope and the destructor is called for clearing out of scope variables.
A simple solution would be to make threads part of the class.
On another note, std::cout is not a synchronized class, when writing your text might be garbled: Is cout synchronized/thread-safe?
Also, when creating your class Example, delete is never called which causes a memory leak.
Your comment here:
void Example::start()
{
std::thread first (&Example::foo, this); // spawn new thread that calls foo()
std::thread second (&Example::bar, this, 5); // spawn new thread that calls bar(0)
// synchronize threads:
//first.join(); // pauses until first finishes
//second.join(); // pauses until second finishes
}
Is wrong.
Not only does the the join pause until the threads finish. But they also allow the thread to be cleaned up. A thread destructor calls terminate while the thread is join-able (ie it is still running). So you must call join() on the thread (to wait for it to finish) before you can allow the destructor to be called.
One of the comments above suggests calling detach(). This detaches the thread of execution from the thread object (thus making it not join-able). This will work (as your code is in infinite loop), but is a bad idea generally. As allowing main() to exit while threads are still running is undefined behavior.
C++, XCode 4.6.3, OSX 10.8.2, deploying on iOS
I am trying to create a timed event.
My thought process was to create a thread, do the timing in it and then at the end have it call another function. This is working however it is pausing the rest of the program.
//Launch a thread
std::thread t1(start_thread);
//Join the thread with the main thread
t1.join();
void start_thread()
{
std::cout << "thread started" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
stop_thread();
}
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
}
Is there a way to do this that doesn't pause program execution?
Update:
I could declare the thread in the header file and join in the stop_thread():
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
ti.join();
}
but that throws:
Type 'std::thread' does not provide a call operator
UPDATE 2: Calling t1.detach() instead of join seems to work.
You're right it works:
Here is an example coming from cpp reference
http://en.cppreference.com/w/cpp/thread/thread/detach
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
Output:
Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.
We see that the concurrent thread ends after the thread caller ends. This is not possible if detach is not called.
Hope that helps, but Jason found the solution.
Use a class instead.
enum{ PAUSED, STARTED, STOPPED };
class AsyncEvent
{
protected:
unsigned char mState;
public:
AsyncEvent():mState(PAUSED){ mThread = std::thread(&AsyncEvent::run,this); }
~AsyncEvent(){ mThread.join(); }
private:
std::thread mThread;
void run()
{
std::cout << "thread started" << std::endl;
while(mState != STOPPED)
{
if(mState == PAUSED)break;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
}
}
void stop()
{
mState = STOPPED;
}
void pause()
{
mState = PAUSED;
}
};
I am playing around with some sockets, thread and mutexes. My question concerns threads and mutexes:
int ConnectionHandler::addNewSocket(){
this->connectionList_mutex.lock();
std::cout << "test1" << std::endl;
this->connectionList_mutex.unlock();
return 0;
}
int ConnectionHandler::main(){
while(true){
this->connectionList_mutex.lock();
std::cout << "test2" << std::endl;
this->connectionList_mutex.unlock();
}
}`
The main function is running in one thread, while the addNewSocket is called by another thread. The problem is, that when addNewSocket is called once (by the second thread), the next unlock by thread 1 (main) will fail with a strange "signal SIGABRT". I have worked two days on this now, but i did not manage to get it fixed, sadly. I hope you can help me.
Edit: ConnectionHandler is a class, that has connectionList_mutex as a member.
Edit: Sometimes i also get this error: "Assertion failed: (ec == 0), function unlock, file /SourceCache/libcxx/libcxx-65.1/src/mutex.cpp, line 44." but it occurs randomly.
Edit: This is the whole class (Reduced to a minimum, should be context independant to a certain degree, but crashes when i put it right after a client connected, and works if i put it right after the start:
class ConnectionHandler{
public:
ConnectionHandler();
int addNewSocket();
private:
int main();
static void start(void * pThis);
std::mutex connectionList_mutex;
};
ConnectionHandler::ConnectionHandler(){
std::thread t(&this->start, this);
t.detach();
}
void ConnectionHandler::start(void * pThis){
ConnectionHandler *handlerThis;
handlerThis = (ConnectionHandler *)pThis;
handlerThis->main();
}
int ConnectionHandler::addNewSocket(){
this->connectionList_mutex.lock();
std::cout << "test1" << std::endl;
this->connectionList_mutex.unlock();
return 0;
}
int ConnectionHandler::main(){
while(true){
this->connectionList_mutex.lock();
std::cout << "test2" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
this->connectionList_mutex.unlock();
}
}
My guess is that your ConnectionHandler object is being destroyed somewhere. Also, you have defined ConnectionHandler::start in a silly way.
First, ConnectionHandler::start should be defined this way:
void ConnectionHandler::start(ConnectionHandler * pThis){
pThis->main();
}
The C++11 ::std::thread class is perfectly capable of preserving the type of the function argument so there is no need to resort to void *.
Secondly, add in this code:
void ConnectionHandler::~ConnectionHandler(){
const void * const meptr = this;
this->connectionList_mutex.lock();
::std::cout << "ConnectionHandler being destroyed at " << meptr << ::std::endl;
this->connectionList_mutex.unlock();
}
And change the constructor to read:
ConnectionHandler::ConnectionHandler(){
const void * const meptr = this;
::std::cout << "ConnectionHandler being created at " << meptr << ::std::endl;
std::thread t(&this->start, this);
t.detach();
}
This will show you when the ConnectionHandler object is being destroyed. And my guess is that your code is destroying it while your detached thread is still running.
The meptr thing is because operator << has an overload for void * that prints out the pointer value. Printing out the pointer value for this will allow you to match up calls to the constructor and destructor if you're creating multiple ConnectionHandler objects.
Edit: Since it turned out I was correct, here is how I would recommend you write the play ConnectionHandler class:
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <mutex>
class ConnectionHandler {
public:
ConnectionHandler();
~ConnectionHandler();
ConnectionHandler(const ConnectionHandler &) = delete;
const ConnectionHandler &operator =(const ConnectionHandler &) = delete;
int addNewSocket();
private:
int main();
static void start(ConnectionHandler * pThis);
::std::mutex connectionList_mutex;
volatile ::std::atomic_bool thread_shutdown;
::std::thread thread;
};
ConnectionHandler::ConnectionHandler()
: thread_shutdown(false), thread(&this->start, this)
{
}
ConnectionHandler::~ConnectionHandler()
{
thread_shutdown.store(true);
thread.join();
}
void ConnectionHandler::start(ConnectionHandler * pThis){
pThis->main();
}
int ConnectionHandler::addNewSocket(){
::std::lock_guard< ::std::mutex> lock(connectionList_mutex);
::std::cout << "test1" << ::std::endl;
return 0;
}
int ConnectionHandler::main(){
while(!thread_shutdown.load()){
::std::lock_guard< ::std::mutex> lock(connectionList_mutex);
::std::cout << "test2" << ::std::endl;
::std::this_thread::sleep_for(::std::chrono::milliseconds(100));
}
return 0;
}