c++调用线程创建函数
时间: 2023-07-30 07:06:00 浏览: 49
在C++中,可以使用以下方法创建线程:
1. 使用C++11的std::thread库:
```
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Hello from thread!\n";
}
int main() {
std::thread t(threadFunction);
t.join();
return 0;
}
```
2. 使用C的pthread库:
```
#include <iostream>
#include <pthread.h>
void* threadFunction(void* arg) {
std::cout << "Hello from thread!\n";
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, threadFunction, NULL);
pthread_join(thread, NULL);
return 0;
}
```
无论使用哪种方法,都需要指定线程函数,并在主函数中创建线程并等待其完成。注意,在使用pthread库时,需要在编译时链接pthread库,可以使用以下命令:
```
g++ -pthread program.cpp -o program
```
相关问题
c++多线程与函数指针
好的,您的问题是:
在 C 中如何使用多线程和函数指针?
答案:
在 C 中,使用多线程需要使用线程库,例如 pthread。使用 pthread 库可以通过创建线程来实现多线程编程。下面是一个使用 pthread 创建线程的例子:
```c
#include <stdio.h>
#include <pthread.h>
void *my_func(void *arg) {
printf("Hello from thread!\n");
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, my_func, NULL);
pthread_join(tid, NULL);
printf("Thread finished.\n");
return 0;
}
```
在上面的例子中,`pthread_create` 函数用于创建一个新的线程,`my_func` 函数是新线程将要执行的函数。`pthread_join` 函数用于等待新线程结束。
关于函数指针,在 C 中我们可以通过定义函数指针变量来调用函数。例如:
```c
#include <stdio.h>
void my_func(int arg) {
printf("my_func is called with arg=%d\n", arg);
}
int main() {
void (*func_ptr)(int);
func_ptr = my_func;
func_ptr(123);
return 0;
}
```
在上面的例子中,我们定义了一个函数指针变量 `func_ptr`,并将其赋值为 `my_func` 函数。然后,我们可以直接调用函数指针变量来调用 `my_func` 函数。
c++类的成员函数创建线程
在C++类中创建线程可以使用类的成员函数来实现,可以将成员函数作为参数传递给线程函数进行调用。要创建一个线程,需要使用C++11标准库中的<thread>头文件中的std::thread类。在类的成员函数中创建线程,需要在函数定义前加上static关键字,因为非静态成员函数需要与类的对象一起调用,而线程无法调用对象。如果函数不是静态的,则需要传递一个指向对象的指针作为函数参数。
具体实现可以先定义一个static成员函数,该函数将作为线程函数,然后在该函数中调用成员函数。在创建线程时,可以使用std::thread构造函数,将该静态成员函数和对象指针作为参数传递给std::thread对象。
例如:
```
#include <iostream>
#include <thread>
class MyClass {
public:
void myFunc() {
std::cout << "This is myFunc." << std::endl;
}
static void threadFunc(MyClass* obj) {
obj->myFunc();
}
};
int main() {
MyClass obj;
std::thread myThread(&MyClass::threadFunc, &obj);
myThread.join();
return 0;
}
```
在上面的例子中,我们定义了一个类MyClass,其中包含一个成员函数myFunc。由于该函数需要在线程中调用,因此我们还定义了一个静态成员函数threadFunc,并在其中调用了myFunc。在main函数中,我们创建了一个MyClass对象obj,并将该对象指针传递给std::thread的构造函数。这将构造一个新的线程,并在新线程中调用threadFunc函数。最后,我们使用myThread.join()函数等待线程结束。
总之,在C++中,使用类的成员函数来创建线程是非常方便和灵活的方法,可以使用这种方法在类中处理多线程任务。