What are the different ways of creating threads in C++?

In C++, there are several ways to create threads:

  1. To use the std::thread class for creating threads, include the header file. Here is an example code.
#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread myThread(threadFunction);
    myThread.join();
    
    return 0;
}
  1. Use the POSIX threading library: You can create threads using the pthread_create function in the POSIX threading library. You need to include the header file. Sample code is as follows:
#include <iostream>
#include <pthread.h>

void* threadFunction(void* arg) {
    std::cout << "Hello from thread!" << std::endl;
    return NULL;
}

int main() {
    pthread_t myThread;
    pthread_create(&myThread, NULL, threadFunction, NULL);
    pthread_join(myThread, NULL);
    
    return 0;
}
  1. In C++11, using the std::async function allows for the asynchronous execution of a function and returns a std::future object, which can be accessed using the get() method. Below is an example code:
#include <iostream>
#include <future>

int threadFunction() {
    std::cout << "Hello from thread!" << std::endl;
    return 42;
}

int main() {
    std::future<int> result = std::async(std::launch::async, threadFunction);
    std::cout << "Result: " << result.get() << std::endl;
    
    return 0;
}

The above are several ways to create threads in C++, the specific choice depends on the actual needs and project environment.

 

More tutorials

multithreading in Java that you need to know(Opens in a new browser tab)

How can concurrent programming be implemented in Python?(Opens in a new browser tab)

Java thread ensuring Java code is thread-safe(Opens in a new browser tab)

The program in Java for displaying “Hello World”(Opens in a new browser tab)

Java Thread Join method(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds