What is the simplest way of making a thread in c++? I want to make one that uses an already declared method to run. Something like:
void task1(){
cout << "Thread started";
}
thread t1 = thread(task1());
I guess I want to make a thread that doesn't require downloading any libraries and that my compiler will most likely be able to compile. And a big question I want answered is, what is c++11? Is it a whole different language, or a bundle of libraries?
C++11 has thread library. A very simple example is:
#include <iostream>
#include <thread>
void task1()
{
std::cout<<"Thread started\n";
}
int main()
{
std::thread t1(task1);
t.join();
}
See http://en.cppreference.com/w/cpp/thread/thread
If you can't use C++11, it depends upon what you are programming for. The following "simple as possible" threading example is written in unmanaged Win32 code, using the CreateThread function:
#include <Windows.h>
#include <tchar.h>
#include <iostream>
using namespace std;
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
WORD numSeconds = 0;
for (;;) {
Sleep(1000);
cout << numSeconds++ << " seconds elapsed in child thread!" << endl;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[]) {
HANDLE hThread;
DWORD threadID;
WORD numSeconds = 0;
cout << "Hello world" << endl;
hThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID);
Sleep(500);
for (;;) {
cout << numSeconds++ << " seconds elapsed in main thread!" << endl;
Sleep(1000);
}
return 0;
}
If you use this approach, remember that the function pointer passed to CreateThread must have the signature:
DWORD ThreadFuncion(LPVOID lpParameter);
You can find the description of that signature on MSDN.
C++ standard gets revised often every few years. Some cool things get added and old things are kept for backward compatibility. Here is some history.
Boost has a very good influence in driving the C++ standard.
Related
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;
}
Firstly, I'm using VS2008 (doesn't support C++11). I can't upgrade and need to use native libraries only because it needs to be compiled on another persons' compiler which I don't have control over.
I would like to run the code automatically after 5 seconds without having to poll how many seconds have elapsed.
This is my incomplete code
#include <windows.h>
#include <iostream>
void runMeAfterFiveSeconds(){
cout<<"I'm activated!"<<endl;
}
void main(){
while(1){
cout<<"hello there!"<<endl;
Sleep(2000);
}
}
Example output
hello there!
hello there! //after 2 seconds
hello there! //after 4 seconds
I'm activated! //after 5 seconds
hello there! //after 6 seconds
hello there! //after 8 seconds
hello there! //after 10 seconds
I'm activated! //after 10 seconds
...
This example shows how to do it using a very simple scheduling algorithm. No spawning of additional threads is required.
#include <stdio.h>
#include <windows.h>
int main(int argc, char ** argv)
{
DWORD now = timeGetTime();
DWORD nextPrintHelloThereTime = now;
DWORD nextPrintImActivatedTime = now+5000;
while(1)
{
now = timeGetTime();
DWORD nextEventTime = (nextPrintHelloThereTime < nextPrintImActivatedTime) ? nextPrintHelloThereTime : nextPrintImActivatedTime;
DWORD millisecondsToSleep = nextEventTime-now;
Sleep(millisecondsToSleep);
now = timeGetTime();
if (now >= nextPrintHelloThereTime)
{
printf("hello there!\n");
nextPrintHelloThereTime += 2000;
}
if (now >= nextPrintImActivatedTime)
{
printf("I'm activated!\n");
nextPrintImActivatedTime += 5000;
}
}
}
It really depends on what code you want to execute and how you want it to be executed.
The very simple way of doing so would be creating a separate thread and Sleep() in it.
So, since you cannot upgrade from Visual Studio 2008 (which, if I remember correctly, does not support C++11), you have to use either native Windows threads or some library implementation like Boost.Thread.
To look up how to use Windows threads, see MSDN documentation on _beginthreadex() function.
A short tutorial about Boost.Thread can bee seen here.
Quick examples of both, taken directly from the links I provided:
1) Windows threads:
// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>
unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );
while ( Counter < 1000000 )
Counter++;
_endthreadex( 0 );
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadID;
printf( "Creating second thread...\n" );
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
printf( "Counter should be 1000000; it is-> %d\n", Counter );
// Destroy the thread object.
CloseHandle( hThread );
}
2) Boost.Thread:
struct callable
{
void operator()();
};
boost::thread copies_are_safe()
{
callable x;
return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK
In the second example, you could as well have used a plain function pointer as boost::thread constructor argument. Moreover, you could use a pointer to function with multiple arguments - a luxury Windows API's threads do not provide.
You're probably just going to need to create a thread like so:
#include <windows.h>
#include <iostream>
#include <thread>
void runMeAfterFiveSeconds(){
while(true){
sleep(5000);
cout<<"I'm activated!"<<endl;
}
}
void main(){
std::thread th(runMeAfterFiveSeconds);
while(1){
cout<<"hello there!"<<endl;
Sleep(2000);
}
}
You're going to have to either make a thread (Coding Orange's answer, probably the better way), or just write it all out.
void runMeAfterFiveSeconds(){
cout << "I'm activated!" <<endl;
}
void main(){
while(1){
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
Sleep(3000);
runMeAfterFiveSeconds();
Sleep(1000);
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
runMeAfterFiveSeconds();
}
}
I just get stuck in this code, I assumed that the code locks the global variable "a" for 30 seconds but the output doesn't satisfy this assumption. Could any one help me figure out why this happens and another question is that is there any function to lock required variable for a specific time, being specified by the programmer. Thank you in advanced for your consideration.
#include <iostream>
#include <ctime>
#include <pthread.h>
#include <time.h>
#include <chrono>
using namespace std;
// std::chrono::seconds interval(100);
timed_mutex test_mutex;
int a = 0;
void * write(void * args)
{
auto start=std::chrono::steady_clock::now();
test_mutex.try_lock_until(start+std::chrono::seconds(30));
a = 2;
cout << "Here is place #" << a << endl;
test_mutex.unlock();
pthread_exit(NULL);
}
int main()
{
auto start=std::chrono::steady_clock::now();
pthread_t check;
pthread_create(&check, NULL, &write, NULL);
test_mutex.try_lock_until(start+std::chrono::seconds(30));
a = 1;
cout << "Here is place #" << a << endl;
test_mutex.unlock();
pthread_join(check, NULL);
return 0;
}
std::timed_mutex::try_lock_until returns either:
true when the mutex is acquired, or
false if it timed out (waited as long as allowed) trying to lock the mutex
Note that this code is buggy anyway, because it doesn't check the return value. So, a can be written even if the mutex was not acquired.
So I am pretty new to threading in general and have been experimenting with pthreads for the past couple of weeks. I have created a class that has a threaded function within itself. It works fine, until I tried to set a class property (an integer) to a value.
.h file:
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <iostream>
#include <windows.h>
using namespace std;
class testClass
{
public:
testClass();
HANDLE h;
static DWORD WINAPI mythread(LPVOID param);
int mytestint;
void printstuffs();
void startThread();
};
#endif // TESTCLASS_H
.cpp file
#include "testClass.h"
testClass::testClass()
{
cout << "Created class" << endl;
}
DWORD WINAPI testClass::mythread(LPVOID param)
{
cout << "In thread" << endl;
testClass* This = (testClass*)param;
cout << "Calling class function" << endl;
This->printstuffs();
cout << "Thread is done" << endl;
return NULL;
}
void testClass::printstuffs()
{
cout << "In class function " << endl;
mytestint = 42; // <- crashes here
cout << "Test Int = " << mytestint << endl;
}
void testClass::startThread()
{
h = CreateThread(NULL, 0, mythread, (LPVOID)0, 0, NULL);
cout << "Thread started" << endl;
}
So why does it crash when I call mytestint = 42; ?
You're calling mythread with a null pointer. When you cast that to This, you end up calling a function on a null object. When you do mytestint = 42, the computer sees it like this->mytestint = 42, and since this is NULL, you dereference a null pointer, and the program segfaults. You need to do something like the following:
h = CreateThread(NULL, 0, mythread, (LPVOID)this, 0, NULL);
If possible, I would also suggest migrating over to standard C++ threads introduced in C++11. Since it looks like you're just learning multithreading it would be useful to learn the standard facilities (which are included with the latest versions of MSVC and GCC) vice vendor-specific APIs.
The way you are implementing the thread call back is not correct. And are you sure that its crashing at the integer assignment, I assume it must be crashing in te first line of your Thread Call back.
You are not passing a reference to "this" in the CreateThread function call.
I am converting a previous thread wrapper around pthreads to std::thread.
However c++11 does not have any way to cancel the thread. I REQUIRE, nonetheless, to cancel threads since they may be performing a very lengthy task inside an external library.
I was considering using the native_handle that gives me pthread_id in my platform. I'm using gcc 4.7 in Linux (Ubuntu 12.10). The idea would be:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main(int argc, char **argv) {
cout << "Hello, world!" << endl;
auto lambda = []() {
cout << "ID: "<<pthread_self() <<endl;
while (true) {
cout << "Hello" << endl;
this_thread::sleep_for(chrono::seconds(2));
}
};
pthread_t id;
{
std::thread th(lambda);
this_thread::sleep_for(chrono::seconds(1));
id = th.native_handle();
cout << id << endl;
th.detach();
}
cout << "cancelling ID: "<< id << endl;
pthread_cancel(id);
cout << "cancelled: "<< id << endl;
return 0;
}
The thread is canceled by an exception thrown by pthreads.
My question is:
Will there be any problem with this approach (besides not being portable)?
No, I don't think that you will not have additional problems than:
not being portable
having to program _very_very_ carefully that all objects of the cancelled thread are destroyed...
For example, the Standard says that when a thread ends variables will be destroyed. If you cancel a thread this will be much harder for the compiler, if not impossible.
I would, therefore recommend not to cancel a thread if you can somehow avoid it. Write a standard polling-loop, use a condition variable, listen on a signal to interrupt reads and so on -- and end the thread regularly.