创建一个线程默认的状态是joinable
thread.Join
把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
join是阻塞当前线程,并等待object对应线程结束,该线程继续执行搜索.
一般用在,主线程等待子线程退出后,一起退出线程。
detach
是将线程从当前线程分离出去,即不受阻塞,操作系统会将其独立对待。
在创建子线程之后,detach该线程ID,该线程不受堵塞。
#include <pthread.h>
#include <iostream>
#include <GLES2/gl2.h>
#include <emscripten.h>
//#include <emscripten/html5_webgl.h>
#include <emscripten/html5.h>
#include <emscripten/threading.h>
pthread_t thread_id1;
pthread_t thread_id2;
#ifdef __cplusplus
extern "C"
#endif
{
EMSCRIPTEN_KEEPALIVE
void *threadFunc(void* arg)
{
std::cout<<"enter thread func"<<std::endl;
return arg;
}
EMSCRIPTEN_KEEPALIVE
void *threadFunc2(void* arg)
{
std::cout<<"enter thread2 func"<<std::endl;
for(int i=0;i<3;i++)
{
std::cout<<"enter 2"<<std::endl;
}
return arg;
}
EMSCRIPTEN_KEEPALIVE
int main() {
int ret = pthread_create(&thread_id1, NULL, threadFunc, NULL);
if(ret)
{
std::cout<<"create thread failed!"<<std::endl;
}
pthread_detach(thread_id1);//分离线程
int ret2 = pthread_create(&thread_id2, NULL, threadFunc2, NULL);
if(ret2)
{
std::cout<<"create thread2 failed!"<<std::endl;
}
pthread_join(thread_id2);
std::cout<<"game over"<<std::endl;
return 0;
}
#ifdef __cplusplus
}
#endif
编译脚本
emcc test.cpp -o test.html -s USE_PTHREADS=1 -s INITIAL_MEMORY=128MB