在C++中,創建線程有以下幾種方式:
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread myThread(threadFunction);
myThread.join();
return 0;
}
#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;
}
#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;
}
以上是在C++中創建線程的幾種方式,具體選擇哪種方式取決于實際需求和項目環境。