Simple Example of Threading in C++

Simple example of threading in C++

Create a function that you want the thread to execute, for example:

void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class.)

The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join();

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)



The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}

int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");

// Do other things...

// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

How to use Multithreading in C?

Please use only lowercase in C to declaring variables and functions
as struct,typeof,sizeof,int,char,void,for,while,etc....

EDIT:
Sorry for not to understand "I thought you need help to do that code in C"

Now i know that you want multi-threading functions to do two jobs or more at the same time without waiting for other to finish.

Okay, to do that you have to

  • include pthread.h which means POSIX Thread

Note: you should notice from this name that this library for Linux OS only

and you compile it with gcc compiler

  • declare variable pthread to for example: tid in your main() as the most popular name
  • Create your function in void *() and type stuff whatever it does then create your thread in main() and assign it your function through that code:

    pthread_create(&tid, NULL, MyThread, NULL);

pthread_create() arguments:

  1. A pointer to a pthread_t structure that we created to fill it with the upcoming arguments.

  2. A pointer to a pthread_attr_t with parameters for the thread. You can safely just pass NULL most of the time.

Note: The pthread_attr_t > "arg 2" should be treated as opaque: any access to
the object other than via pthreads functions is nonportable and
produces undefined results.


  1. Take the function that you created as thread and shall be with no return and

    points to >> void, that's why we created void *()

Note: Type only the name of function without (), you will know why in the next argument


  1. Here you passing your arguments to your function!, if there's no arguments just pass NULL

Example Code:

#include <stdio.h>
#include <pthread.h>
int i=0,x=0; //Initialize our variables
void *MyThread(void *ANYarg) //arguments must be a pointers to point from `pthread_create` with `NULL` if no need
{
while(1) //background thread
{
i++;
x++;
}
return NULL;
}

int main()
{
char *input;
pthread_t tid; //Declare a thread
pthread_create(&tid, NULL, MyThread, NULL); //Create the thread
while(1) //Printing thread , Uncover increamting of variables
{
scanf("%s",&input); //whenever you input a value
printf("i: %d, x: %d\n",i,x);//will print the i,x values now
}
return 0;
}

Note: You should at least create one pointer variable specifically to your thread function cause fourth argument of pthread_create() need at least one to pass the NULL value

You can wait for an thread to finish instead of doing work at the same time through that code line:

pthread_join(tid, NULL);

Should return 0 when success

An Example:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *MyCoolthread(void *vargp)
{
printf("Yes..see me printing success after 3 seconds \n");
sleep(3);
printf("Success! \n");
return NULL;
}

int main()
{
pthread_t tid;
printf("Hello, are you there? \n");
sleep(1);
pthread_create(&tid, NULL, MyCoolthread, NULL);
pthread_join(tid, NULL);
printf("Yup i see!\n");
return 0;
}

Try to comment pthread_join(tid, NULL); with // to see what happens

and to terminate your thread is through code line:

pthread_exit(&tid);

Doesn't return to its caller any value

Edit: I noticed now that you use windows so i advice you to dual boot with Ubuntu instead if you really interested in C

otherwise you can use multi-threading in windows.h header that called winapi library but i'm not expert in so you can find an simple example here and you should mentioned in your post that you want for windows by the way you can edit to improve it

I tried my best to get it clear, hope it helps.

c++: simple multi-threading example not faster than single thread

clock() measures processor time, the time that your process spent on your cpu. In a multi-thread program it will add up time each thread spent on your cpu. Your single-thread and multi-thread implementations are reported to take about same time to run, since they are doing equal number of calculations overall.

What you need is to measure wall clock time. Use chrono library when you want to measure wall clock time.

#include <chrono>

int main ()
{
auto start = std::chrono::high_resolution_clock::now();

// code section

auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration<double, std::milli>(end - start).count() << " ms\n";
}

Using threads in C on Windows. Simple Example?

Here is the MSDN sample on how to use CreateThread() on Windows.

The basic idea is you call CreateThread() and pass it a pointer to your thread function, which is what will be run on the target thread once it is created.

The simplest code to do it is:

#include <windows.h>

DWORD WINAPI ThreadFunc(void* data) {
// Do stuff. This will be the first function called on the new thread.
// When this function returns, the thread goes away. See MSDN for more details.
return 0;
}

int main() {
HANDLE thread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
if (thread) {
// Optionally do stuff, such as wait on the thread.
}
}

You also have the option of calling SHCreateThread()—same basic idea but will do some shell-type initialization for you if you ask it, such as initializing COM, etc.

C++ 11 thread simple example

They're all there. They're just mangled up because the console output happens in vaguely random orders.

In particular have a look at the end of the first line of output.

What is a basic example of low-level multi-threading in C++?

The canonical implementation of "low level threads" is pthreads. The most basic examples of threading problems that are usually taught along with pthreads are some form of readers and writers problem. That page also links to more classical threading problems like producers/consumers and dining philosophers.

Behaviour of simple multithread program on C++

A spotted in the comments, the source of the main issue of your code is that you call pthread_detach.

The later pthread_join will just ignore the thread you detach.

At this point all thread "live their own life" which means the the only remaining synchronization mechanism is at the "exit" (when main returns). On exit, the compiler added some code that will wait for all threads to terminate.

So as threads are not synchronized in any way, what is happening is just a race condition.

When adding the usleep, you just delay the fist thread enough for the other one to have much time to finish first.

When no usleep, the race just produces random order of logs.

Worth to notice that stdout is bufferized, so the output may not be displayed at the time the printf call is done.

Remove the pthread_detach() will restore the synchro provided by pthread_join, so the log will appea in the order you expect (if I put aside the stdout bufferization pb)

Threading queue in c++

You are giving each thread its own copy of the queue. I imagine that what you want is all the threads to work on the same queue and for that you will need to use some synchronization mechanism when multiple threads work on the shared queue as std queue is not thread safe.

edit: minor note: in your code you are spawning 11 threads not 10.

edit 2: OK, try this one to begin with:

std::mutex lock_work;
std::mutex lock_io;

void Test(queue<string>& queue){

while (!queue.empty()) {
string proxy;
{
std::lock_guard<std::mutex> lock(lock_work);
proxy = queue.front();
queue.pop();
}
{
std::lock_guard<std::mutex> lock(lock_io);
cout << proxy << "\n";
}
}

}



Related Topics



Leave a reply



Submit