目录
Android jni调用多线程
#include <jni.h>
#include <thread>
#include <android/log.h>
#define LOG_TAG "FaceRecognitionThread"
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
void faceRecognitionTask() {
ALOGD("Face recognition thread started");
while (true) {
ALOGD("Running face recognition");
std::this_thread::sleep_for(std::chrono::seconds(1));
if (/* termination condition */) {
break;
}
}
ALOGD("Face recognition thread exiting");
}
extern "C" JNIEXPORT void JNICALL
Java_com_example_myapp_MainActivity_startFaceRecognition(JNIEnv* env, jobject thiz) {
std::thread t(faceRecognitionTask);
t.detach(); // 让线程在后台运行并自行结束
}
需要结果的多线程
未测试
#include <thread>
#include <iostream>
void backgroundTask() {
while (true) {
// 执行一些后台任务,比如数据处理
std::cout << "Processing data in background..." << std::endl;
// 检查是否接收到终止信号,如果是,则退出循环
if (shouldTerminate()) break;
// 模拟处理时间
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::thread worker(backgroundTask);
worker.detach();
std::cout << "Main thread continues..." << std::endl;
// 执行主线程的其他任务
std::this_thread::sleep_for(std::chrono::seconds(10));
// 发送终止信号给后台线程
sendTerminateSignal();
std::cout << "Main thread ends." << std::endl;
return 0;
}
在这个例子中,主线程在创建和分离工作线程后继续执行,不会被工作线程的长时间运行任务阻塞。同时,工作线程定期检查是否收到了终止信号,以便适时结束执行。这种设计保证了主线程的流畅执行,同时提供了对后台任务适当的控制。
Windows 多线程
std thread比较好用,但是系统带的socket不能调用recv
createthread 函数在mfc界面不报错,在application.cpp中报错:
BOOL CMFCApplication1App::InitInstance()
{
HANDLE h_thread= CreateThread(NULL, 0, Fun, NULL, 0, NULL);//创建多线程
CloseHandle(h_thread);
}
用户界面线程经常重载该函数,工作者线程一般不使用 InitInstance()
在Python下面主线程下调用这个会报错,但是如果在qthread下面调用,则正常运行。
E:\c++\MFCApplication1\MFCApplication1\MFCApplication1.cpp
“CWinThread::CreateThread”: 函数不接受 6 个参数 MFCApplication1
因为用的是 afxwin.h中的接口,本来接口是processthreadsapi.h的接口
c:\Program Files (x86)\Windows Kits\8.1\Include\um\processthreadsapi.h
解决方法:在Frm.cpp中使用可能就好了
mfc 用的 AfxBeginThread函数