C++中,可以使用std::thread库创建线程,并使用函数指针或lambda表达式作为回调函数。以下是一个示例代码,其中包含两个线程和其各自的回调函数:
#include <iostream>
#include <thread>
void thread_callback_1(int count) {
for (int i = 0; i < count; i++) {
std::cout << "Thread 1: " << i << std::endl;
}
}
void thread_callback_2(int count) {
for (int i = 0; i < count; i++) {
std::cout << "Thread 2: " << i << std::endl;
}
}
int main() {
int count = 10;
std::thread t1(thread_callback_1, count);
std::thread t2(thread_callback_2, count);
t1.join();
t2.join();
return 0;
}
在上述代码中,我们首先定义了两个回调函数thread_callback_1和thread_callback_2,分别用于处理两个线程的逻辑。然后,在main函数中,我们使用std::thread库创建了两个线程t1和t2,并将它们绑定到相应的回调函数上,同时传入count参数作为回调函数的参数。最后,我们调用join方法等待线程执行完毕。
需要注意的是,在多线程编程中,需要考虑线程安全性问题,如对共享资源的访问等。此处仅为简单示例,实际项目中需根据具体情况进行更严格的处理。