Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C++ Threading

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)

like image 743
Jon Tackabury Avatar asked Feb 27 '09 20:02

Jon Tackabury


People also ask

What is threading in C?

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications.

How do you create a thread in C?

In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread. pthread_create() takes 4 arguments.

Is C single threaded?

C is a language that runs on one thread by default, which means that the code will only run one instruction at a time.

How do PThreads work?

Pthread uses sys_clone() to create new threads, which the kernel sees as a new task that happens to share many data structures with other threads. To do synchronization, pthread relies heavily on futexes in the kernel.


1 Answers

#include <boost/thread.hpp>

static boost::thread runStuffThread;

static void MyMethod(int data)
{
    runStuffThread = boost::thread(boost::bind(RunStuff, data));
}

// elsewhere...
runStuffThread.join(); //blocks
like image 80
greyfade Avatar answered Sep 22 '22 22:09

greyfade