Simple C++ Threading - c++

I am trying to create a thread in C++ (Win32) to run a simple method. I'm new to C++ threading, but very familiar with threading in C#. Here is some pseudo-code of what I am trying to do:
static void MyMethod(int data)
{
RunStuff(data);
}
void RunStuff(int data)
{
//long running operation here
}
I want to to call RunStuff from MyMethod without it blocking. What would be the simplest way of running RunStuff on a separate thread?
Edit: I should also mention that I want to keep dependencies to a minimum. (No MFC... etc)

#include <boost/thread.hpp>
static boost::thread runStuffThread;
static void MyMethod(int data)
{
runStuffThread = boost::thread(boost::bind(RunStuff, data));
}
// elsewhere...
runStuffThread.join(); //blocks

C++11 available with more recent compilers such as Visual Studio 2013 has threads as part of the language along with quite a few other nice bits and pieces such as lambdas.
The include file threads provides the thread class which is a set of templates. The thread functionality is in the std:: namespace. Some thread synchronization functions use std::this_thread as a namespace (see Why the std::this_thread namespace? for a bit of explanation).
The following console application example using Visual Studio 2013 demonstrates some of the thread functionality of C++11 including the use of a lambda (see What is a lambda expression in C++11?). Notice that the functions used for thread sleep, such as std::this_thread::sleep_for(), uses duration from std::chrono.
// threading.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
int funThread(const char *pName, const int nTimes, std::mutex *myMutex)
{
// loop the specified number of times each time waiting a second.
// we are using this mutex, which is shared by the threads to
// synchronize and allow only one thread at a time to to output.
for (int i = 0; i < nTimes; i++) {
myMutex->lock();
std::cout << "thread " << pName << " i = " << i << std::endl;
// delay this thread that is running for a second.
// the this_thread construct allows us access to several different
// functions such as sleep_for() and yield(). we do the sleep
// before doing the unlock() to demo how the lock/unlock works.
std::this_thread::sleep_for(std::chrono::seconds(1));
myMutex->unlock();
std::this_thread::yield();
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
// create a mutex which we are going to use to synchronize output
// between the two threads.
std::mutex myMutex;
// create and start two threads each with a different name and a
// different number of iterations. we provide the mutex we are using
// to synchronize the two threads.
std::thread myThread1(funThread, "one", 5, &myMutex);
std::thread myThread2(funThread, "two", 15, &myMutex);
// wait for our two threads to finish.
myThread1.join();
myThread2.join();
auto fun = [](int x) {for (int i = 0; i < x; i++) { std::cout << "lambda thread " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } };
// create a thread from the lambda above requesting three iterations.
std::thread xThread(fun, 3);
xThread.join();
return 0;
}

CreateThread (Win32) and AfxBeginThread (MFC) are two ways to do it.
Either way, your MyMethod signature would need to change a bit.
Edit: as noted in the comments and by other respondents, CreateThread can be bad.
_beginthread and _beginthreadex are the C runtime library functions, and according to the docs are equivalent to System::Threading::Thread::Start

Consider using the Win32 thread pool instead of spinning up new threads for work items. Spinning up new threads is wasteful - each thread gets 1 MB of reserved address space for its stack by default, runs the system's thread startup code, causes notifications to be delivered to nearly every DLL in your process, and creates another kernel object. Thread pools enable you to reuse threads for background tasks quickly and efficiently, and will grow or shrink based on how many tasks you submit. In general, consider spinning up dedicated threads for never-ending background tasks and use the threadpool for everything else.
Before Vista, you can use QueueUserWorkItem. On Vista, the new thread pool API's are more reliable and offer a few more advanced options. Each will cause your background code to start running on some thread pool thread.
// Vista
VOID CALLBACK MyWorkerFunction(PTP_CALLBACK_INSTANCE instance, PVOID context);
// Returns true on success.
TrySubmitThreadpoolCallback(MyWorkerFunction, context, NULL);
// Pre-Vista
DWORD WINAPI MyWorkerFunction(PVOID context);
// Returns true on success
QueueUserWorkItem(MyWorkerFunction, context, WT_EXECUTEDEFAULT);

Simple threading in C++ is a contradiction in terms!
Check out boost threads for the closest thing to a simple approach available today.
For a minimal answer (which will not actually provide you with all the things you need for synchronization, but answers your question literally) see:
http://msdn.microsoft.com/en-us/library/kdzttdcb(VS.80).aspx
Also static means something different in C++.

Is this safe:
unsigned __stdcall myThread(void *ArgList) {
//Do stuff here
}
_beginthread(myThread, 0, &data);
Do I need to do anything to release the memory (like CloseHandle) after this call?

Another alternative is pthreads - they work on both windows and linux!

CreateThread (Win32) and AfxBeginThread (MFC) are two ways to do it.
Be careful to use _beginthread if you need to use the C run-time library (CRT) though.

For win32 only and without additional libraries you can use
CreateThread function
http://msdn.microsoft.com/en-us/library/ms682453(VS.85).aspx

If you really don't want to use third party libs (I would recommend boost::thread as explained in the other anwsers), you need to use the Win32API:
static void MyMethod(int data)
{
int data = 3;
HANDLE hThread = ::CreateThread(NULL,
0,
&RunStuff,
reinterpret_cast<LPVOID>(data),
0,
NULL);
// you can do whatever you want here
::WaitForSingleObject(hThread, INFINITE);
::CloseHandle(hThread);
}
static DWORD WINAPI RunStuff(LPVOID param)
{
int data = reinterpret_cast<int>(param);
//long running operation here
return 0;
}

There exists many open-source cross-platform C++ threading libraries you could use:
Among them are:
Qt
Intel
TBB Boost thread
The way you describe it, I think either Intel TBB or Boost thread will be fine.
Intel TBB example:
class RunStuff
{
public:
// TBB mandates that you supply () operator
void operator ()()
{
// long running operation here
}
};
// Here's sample code to instantiate it
#include <tbb/tbb_thread.h>
tbb::tbb_thread my_thread(RunStuff);
Boost thread example:
http://www.ddj.com/cpp/211600441
Qt example:
http://doc.trolltech.com/4.4/threads-waitconditions-waitconditions-cpp.html
(I dont think this suits your needs, but just included here for completeness; you have to inherit QThread, implement void run(), and call QThread::start()):
If you only program on Windows and dont care about crossplatform, perhaps you could use Windows thread directly:
http://www.codersource.net/win32_multithreading.html

Related

Thread-safe CreateThread?

Is the PrintHello() function pthreads example thread-safe? I find these kind of examples online but I don't understand how they can be thread-safe. On the other hand, if I add a mutex around the code in PrintHello() function then the example would not be multithreaded as all threads would queue in wait for the previous thread to exit the PrintHello() function. Also, moving it to a class would not help as the member would have to be statically declared as pointers to non-static functions is not allowed with CreateThread() it seems. Any way of solving this?
#include <WinBase.h>
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#define NUM_THREADS 500
DWORD PrintHello(LPVOID oHdlRequest)
{
long tid;
tid = (long)GetCurrentThreadId();
/* randomly sleep between 1 and 10 seconds */
int sleepTime = rand() % 10 + 1;
sleep(sleepTime);
printf("Hello World! It's me, thread #%ld!\n", tid);
return 0;
}
int main (int argc, char *argv[])
{
/* initialize random seed: */
srand (time(NULL));
HANDLE threads[NUM_THREADS];
long t;
DWORD nThreadID;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
threads[t] = CreateThread(
// Default security
NULL,
// Default stack size
0,
// Function to execute
(LPTHREAD_START_ROUTINE)&PrintHello,
// Thread argument
NULL,
// Start the new thread immediately
0,
// Thread Id
&nThreadID
);
if (!threads[t]){
printf("ERROR; return code from CreateThread() is %d\n", GetLastError());
exit(-1);
}
}
}
Since you're including WinBase.h, I'll assume that you're using MSVC. MSVC CRT has long supported multithreaded access - in fact, current versions of MSVC no longer support a single threaded CRT that isn't threadsafe. I believe that VS 2003 is the last version of MSVC that supported the single threaded CRT.
In the multithreaded CRT, functions are threadsafe and if they access global data internally they will synchronize among themselves. So each printf() executed in ProcessRequest() will be atomic with respect to other printf() calls in other threads (actually, the locks are based on streams, so the printf() calls will be atomic with respect to other CRT functions that use stdout).
The exceptions to this are if you use I/O functions that are explicitly documented to not take locks (so you can synchronize on them yourself for performance reasons), or if you define _CRT_DISABLE_PERFCRIT_LOCKS in which case the CRT assumes that all I/O will be performed on a single thread.
See http://msdn.microsoft.com/en-us/library/ms235505.aspx
POSIX makes similar guarantees that printf() will be threadsafe:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/flockfile.html
All functions that reference (FILE *) objects, except those with names ending in _unlocked, shall behave as if they use flockfile() and funlockfile() internally to obtain ownership of these (FILE *) objects.
http://newsgroups.derkeiler.com/Archive/Comp/comp.programming.threads/2009-06/msg00058.html (A post by David Butenhof):
POSIX/UNIX requires that printf() itself be atomic; it's not legal that two parallel calls to printf() from separate threads can mix their data. But those two writes may appear on the output in either order.
The code is not thread-safe in general; printf is not normally
reentrant. (An implementation could add reentrace to it as
an additional feature, but I don't know of any which do.) You
must add some sort of protection around it. (Under Windows,
a so called CriticalSection should be sufficient.)
You'll also have to find a thread safe alternative to sleep;
I can't find any documentation which says that it is reentrant
(and the Posix variant isn't), but Microsoft doesn't seem to
document reentrance in general. A classical solution for this
would be to create a Mutex, block it, and then call
WaitForSingleObject on it with the desired timeout;
CreateWaitableTimer and WaitForSingleObject should work as
well. (As I said, Microsoft's documentation is very deficient;
but WaitForSingleObject must be safe, since it is des igned to
be used when waiting for a mutex, among other things.)
Note too that unless you join the created threads, you'll
probably run off the end of main, and the process will
terminate before any of the threads will have run. (Under
Windows, you can use WaitForSingleObject or
WaitForMultipleObjects to join.)
An even better solution would be to the standard threads, if you
have a compiler which supports them, or Boost threds, if you
don't.

Obtaining thread Core affinity in C++ 11 through pthreads

I'm trying to set core affinity (Thread #1 goes on first core, Thread #2 goes on second core, ...) while using std::thread in C++ 11.
I've already searched around various topics and on the internet and it seems C++ 11 API doesn't provide such low level feature.
On the other hand, pthreads come with pthread_setaffinity_np which would be useful if I could get the "pthread_t" value of my std::thread (I don't know if this is human reasonable or at least legitimate asking for it).
An example program of what I'd want to have in the end is this:
#include <thread>
#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define CORE_NO 8
using namespace std;
void run(int id) {
cout << "Hi! I'm thread " << id << endl;
// thread function goes here
}
int main() {
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for(int i=0; i<CORE_NO; i++)
CPU_SET(i, &cpu_set);
thread t1(run, 1);
// obtaining pthread_t from t1
/*
pthread_t this_tid = foo(t1);
pthread_setaffinity_np(this_tid, sizeof(cpu_set_t), &cpu_set);
*/
t1.join();
return 0;
}
I'd really prefer not to change the whole architecture of my project (which must provide such characteristic). I've now a massive use of std::thread but I can use pthread API in addition as well, as you have seen in the example.
Is there a way for me to solve this problem?
You can get the native handle for the thread with the native_handle function.
The example in the linked reference even uses this to call pthread functions.
I do not know if it is a suitable approach in your case, but what I usually do is to call the affinity primitives from within the thread. E.g., I place a snippet of code similar to this one somewhere at the beginning of the threaded function:
const int err = pthread_setaffinity_np(pthread_self(),...);
The call to pthread_self() will return the ID of the calling thread.

Threading in C++ to keep two functions running parallely

I have a code congaing two functions func1 and func2. Role of both the function is same. Keep reading a directory continuously and write the names of file present in their respective log files. Both functions are referring a common log function to write the logs. I want to use introduce threading in my code such that both of them keep on running parallely but both should not access the log function at same time. How to achieve that?
This is a classic case of needing a mutex.
void WriteToLog(const char *msg)
{
acquire(mutex);
logfile << msg << endl;
release(mutex);
}
The above code won't "copy and paste" into your system, since mutexes are system specific - pthread_mutex would be the choice if you are using pthreads. C++11 has it's own mutex and thread functionality, and Windows has another variant.
From Sajal's comments:
tried pthread_create(&thread1, NULL, start_opca, &opca); pthread_join( thread1, NULL); pthread_create(&thread2, NULL, start_ggca, &ggca); pthread_join( thread2, NULL);
But the problem with this is that it will wait for one thread to finish before starting next. I don't want that.
the join function blocks the calling thread, until the thread you call join for, finishes. In your case, calling join on the first thread before creating the second, guarantees that the first thread will end before the second one begins.
You should create the two threads first, then join them both (instead of interspersing the creations and join of both).
Additionally, the access to the log should be extracted into common code for both (a logging function, a logging class etc. Within the extracted code, the log access should be guarded using a mutex.
If you have an implementation (partially) supporting c++11, you should use std::thread and std::mutex for this. Otherwise, you should use boost::thread. If you have access to neither, use pthreads under linux.
On linux, you will need to use pthreads
Since both threads are reading/writing from/to I/O (reading dirs and writing log files) there's no need for multi-threading: you gain no speed improvement parallelizing the task since every I/O access is enqueued at lower levels.
This C language Code may give you some hint. To answer your question:
You should use mutex in pthread to make sure that the log file could only be access by one thread at the same time.
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t LogLock = PTHREAD_MUTEX_INITIALIZER;
char* LogFileName= "test.log";
void* func_tid0( void* a) {
int i;
for(i=0; i < 50; i++ ) {
pthread_mutex_lock(&LogLock);
fprintf((FILE*)a, "write to log by thread0:%d\n", i);
pthread_mutex_unlock(&LogLock);
}
}
void* func_tid1(void* a) {
int i;
for(i=0; i < 50; i++ ) {
pthread_mutex_lock(&LogLock);
fprintf((FILE*)a, "write to log by thread1:%d\n", i);
pthread_mutex_unlock(&LogLock);
}
}
int main() {
pthread_t tid0, tid1;
FILE* fp=fopen(LogFileName, "wb+");
pthread_create(&tid0, NULL, func_tid0, (void*) fp );
pthread_create(&tid1, NULL, func_tid1, (void*) fp );
void* ret;
pthread_join(tid0, &ret);
pthread_join(tid1, &ret);
}
Your another question isn't exist.
Because the main thread is suspend at your first pthread_join, but it's not mean the second thread doesn't run. Actually the second thread is beginning at pthread_create(thread1).
And actually pthread_mutex casuses your program serial.

Is there anything like timer and timertask in c++ just like java has?

I am not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create example that is in man page of timer_create but It is not working as per my requirement.
I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.
Any help would be highly appreciated.
Thanks,
Yuvi.
I too was looking for a Java like TimerTask but I needed one for Windows C++ when I came across this question. After a day of researching mostly on SO and learning about passing class member functions, I was able to put together a solution that seems to work well for me. I realize that I am years late in answering this question but maybe someone still looking for this solution will find this useful.
This is a Windows only solution which I tested on Windows 10 using Visual Studio C++. I'm still learning C++ so please be gentle if I've broken any rules. I realize the exceptions are elementary but they are easy to customize to your needs. I created a TimerTask class similar to the Java class. You'll need to derive a new user class from the TimerTask class and create a "task" function that includes the code you want executed at regular intervals. Here is the TimerTask class:
--TimerTask.h--
#pragma once
#include <thread>
class TimerTask {
HANDLE timeoutEvent;
DWORD msTimeout;
bool exit = false;
void* pObj;
static void taskWrapper(TimerTask* pObj) {
while (!pObj->exit) {
DWORD waitResult = WaitForSingleObject(pObj->timeoutEvent, pObj->msTimeout);
if (pObj->exit)
break;
pObj->task();
}
}
public:
TimerTask::TimerTask() {
timeoutEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!timeoutEvent) {
throw "TimerTask CreateEvent Error: ";
}
}
TimerTask::~TimerTask() {
CloseHandle(timeoutEvent);
}
// Derived class must create task function that runs at every timer interval.
virtual void task() = 0;
void start(void* pObj, DWORD msTimeout) {
this->pObj = pObj;
this->msTimeout = msTimeout;
std::thread timerThread(taskWrapper, (TimerTask*)pObj);
timerThread.detach();
}
void stop() {
exit = true;
if (!SetEvent(timeoutEvent))
throw "TimerTask:stop(): Error: ";
}
};
And here is a sample of usage. For brevity I didn't include error checking.
--Test.cpp--
#include "Windows.h"
#include <iostream>
#include "TimerTask.h"
using namespace std;
class KeepAliveTask : public TimerTask {
public:
void task() {
cout << "Insert your code here!\n";
}
};
int main()
{
cout << "Hello, TimerTask!\n";
KeepAliveTask keepAlive;
keepAlive.start(&keepAlive, 1000); // Execute once per second
Sleep(5100); // Pause 5.1s to give time for task thread to run.
keepAlive.stop();
Sleep(1000); // Pause another sec to give time for thread to stop.
return 0;
}
This is generally a very difficult question, since you are inherently asking for some concurrent, or at least asynchronous processing.
The simplest, single-threaded solution is to use something like Posix's alarm(2). This will cause a signal to be sent to your process after a specified time. You need to register a signal handler (e.g. with signal(2)), but you are subject to all its limitations (e.g. you must only call async-safe functions within the handler).
A second, single-threaded option is to use a select-style (or epoll-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.
Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.
Some higher-level libraries like Boost.ASIO and the new standard library provide some nice timing mechanisms once you've decided to go down the multithreaded route.

How do I make a function asynchronous in C++?

I want to call a function which will be asynchronous (I will give a callback when this task is done).
I want to do this in single thread.
This can be done portably with modern C++ or even with old C++ and some boost. Both boost and C++11 include sophisticated facilities to obtain asynchronous values from threads, but if all you want is a callback, just launch a thread and call it.
1998 C++/boost approach:
#include <iostream>
#include <string>
#include <boost/thread.hpp>
void callback(const std::string& data)
{
std::cout << "Callback called because: " << data << '\n';
}
void task(int time)
{
boost::this_thread::sleep(boost::posix_time::seconds(time));
callback("async task done");
}
int main()
{
boost::thread bt(task, 1);
std::cout << "async task launched\n";
boost::this_thread::sleep(boost::posix_time::seconds(5));
std::cout << "main done\n";
bt.join();
}
2011 C++ approach (using gcc 4.5.2, which needs this #define)
#define _GLIBCXX_USE_NANOSLEEP
#include <iostream>
#include <string>
#include <thread>
void callback(const std::string& data)
{
std::cout << "Callback called because: " << data << '\n';
}
void task(int time)
{
std::this_thread::sleep_for(std::chrono::seconds(time));
callback("async task done");
}
int main()
{
std::thread bt(task, 1);
std::cout << "async task launched\n";
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "main done\n";
bt.join();
}
As of C++11, plain c++ does have a concept of threads, but the most concise way to call a function asynchronously is to use the C++11 async command along with futures. This ends up looking a lot like the way you'd do the same thing in pthreads, but it's 100% portable to all OSes and platforms:
Say your function has a return value... int = MyFunc(int x, int y)
#include <future>
Just do:
// This function is called asynchronously
std::future<int> EventualValue = std::async(std::launch::async, MyFunc, x, y);
Catch? How do you know when it's done? (The barrier.)
Eventually, do:
int MyReturnValue = EventualValue.get(); // block until MyFunc is done
Note it's easy to do a parallel for loop this way - just create an array of futures.
You can't in plain C++. You'll need to use an OS-specific mechanism, and you need a point where execution is suspended in a way that allows the OS to execute the callback. E.g. for Windows, QueueUserAPC - the callback will be executed when you e.g. SleepEx or WaitForSingleObjectEx
The long answer involves implementing your own task scheduler and wrapping your "function" up into one or more tasks. I'm not sure you want the long answer. It certainly doesn't allow you to call something, completely forget about it, and then be notified when that thing is done; however if you are feeling ambitious, it will allow you to simulate coroutines on some level without reaching outside of standard C++.
The short answer is that this isn't possible. Use multiple threads or multiple processes. I can give you more specific information if you divulge what OS/platform you're developing for.
There are two bits to doing this.
Firstly, packing up the function call so that it can be executed later.
Secondly, scheduling it.
It is the scheduling which depends on other aspects of the implementation. If you know "when this task is done", then that's all you need - to go back and retrieve the "function call" and call it. So I am not sure this is necessarily a big problem.
The first part is then really about function objects, or even function pointers. The latter are the traditional callback mechanism from C.
For a FO, you might have:
class Callback
{
public:
virtual void callMe() = 0;
};
You derive from this and implement that as you see fit for your specific problem. The asyncronous event queue is then nothing more than a list<> of callbacks:
std::list<Callback*> asyncQ; // Or shared_ptr or whatever.
I'm not sure I understand what you want, but if it's how to make use of a callback: It works by defining a function pointer, like this (untested):
// Define callback signature.
typedef void (*DoneCallback) (int reason, char *explanation);
// A method that takes a callback as argument.
void doSomeWorkWithCallback(DoneCallback done)
{
...
if (done) {
done(1, "Finished");
}
}
//////
// A callback
void myCallback(int reason, char *explanation)
{
printf("Callback called with reason %d: %s", reason, explanation);
}
/////
// Put them together
doSomeWortkWithCallback(myCallback);
As others have said, you technically can't in plain C++.
However, you can create a manager that takes your task and does time-slicing or time scheduling; with each function call, the manager uses a timer to measure the amount of time the process took; if the process took less time than scheduled, and it thinks it can finish another call and use up the remaining time without going over, it can call it again; if the function does go over the alloted time, it means the function has less time next update to run. So, this will involve creating a somewhat complex system to handle it for you.
Or, if you have a specific platform in mind, you could use threading, or create another process to handle the work.