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;
}
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!)
I am trying to implement a graceful shutdown of a process when its output is being piped to another process. I am testing the code bellow by piping its output: ./a.out | less and pressing q when a prompt appears. Instead of expected completion of sigwait() I see invocation of signal handler instead (it is added here just to show what is going on).
#include <csignal>
#include <chrono>
#include <iostream>
#include <thread>
#include <signal.h>
int handlerSig {0};
void signalHandler(int s)
{
handlerSig = s;
std::cerr << "handlerSig: " << handlerSig << std::endl;
}
int main()
{
for (int i = 1; i < 32; ++i)
{
std::signal(i, signalHandler);
}
bool run {true};
std::thread thread {[&]
{
while (run)
{
std::cout << "ping" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds {500});
}
}};
sigset_t waitSet;
sigemptyset(&waitSet);
sigaddset(&waitSet, SIGINT);
sigaddset(&waitSet, SIGPIPE);
sigaddset(&waitSet, SIGTERM);
pthread_sigmask(SIG_BLOCK, &waitSet, nullptr);
int waitSig {0};
sigwait(&waitSet, &waitSig);
run = false;
thread.join();
std::cerr << "waitSig: " << waitSig << std::endl;
}
I get consistent results on WSL2 and CentOS machine and I would prefer to focus on solving this problem there. When running under WSL1, neither SIGINT nor SIGTERM cause completion of sigwait() unless I remove pthread_sigmask(SIG_BLOCK...), but that seems to contradict my understanding how sigwait() is supposed to be used.
You'll need to contrive some other way of noticing that the write failed, for example, ignoring SIGPIPE but setting std::cout.exceptions(ios::badbit), or handling the signal within your writing thread.
Importantly, that SIGPIPE will always be generated for your writing thread, your sigwait()ing thread notwithstanding. Certain signals arising from a thread's activity are generated exclusively for that thread, meaning they'll be delivered to or accepted by that thread only. (POSIX.1-2008 System Interfaces 2.4.1) Typically, "naturally occurring" SIGPIPEs, SIGFPEs, and SIGSEGVs work like this.
This is an example of forwarding SIGPIPE to the main thread - probably sufficient in my case:
#include <csignal>
#include <chrono>
#include <iostream>
#include <thread>
#include <signal.h>
pthread_t mainThread {pthread_self()};
void forwardSig(int sig)
{
if (not pthread_equal(pthread_self(), mainThread))
{
pthread_kill(mainThread, sig);
}
}
int main()
{
struct sigaction newAction {};
sigemptyset(&newAction.sa_mask);
newAction.sa_handler = forwardSig;
sigaction(SIGPIPE, &newAction, nullptr);
bool run {true};
std::thread thread {[&]
{
while (run)
{
std::cout << "ping" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds {500});
}
}};
sigset_t waitSet;
sigemptyset(&waitSet);
sigaddset(&waitSet, SIGINT);
sigaddset(&waitSet, SIGPIPE);
sigaddset(&waitSet, SIGTERM);
pthread_sigmask(SIG_BLOCK, &waitSet, nullptr);
int waitSig {0};
sigwait(&waitSet, &waitSig);
run = false;
thread.join();
std::cerr << "waitSig: " << waitSig << std::endl;
}
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'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;
}
I have the book "beyond the C++ standard library" and there are no examples of multithreading using boost. Would somebody be kind enough to show me a simple example where two threads are executed using boost- lets say asynchronously?
This is my minimal Boost threading example.
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction()
{
int counter = 0;
for(;;)
{
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main()
{
// Start thread
boost::thread t(&ThreadFunction);
// Wait for Enter
char ch;
cin.get(ch);
// Ask thread to stop
t.interrupt();
// Join - wait when thread actually exits
t.join();
cout << "main: thread ended" << endl;
return 0;
}