64,648
社区成员
发帖
与我相关
我的任务
分享
如果调用pthread_exit()的话,只会使主函数所在的线程(可以说是进程的主线程)退出;而如果是return,从而导致进程及其所有线程结束运行
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
using namespace std;
int flag=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void* thread1(void *var);
void* thread2(void *var);
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,thread1,&tid2);
pthread_create(&tid2,NULL,thread2,NULL);
pthread_exit(NULL);
pthread_cond_wait(&cond,&mutex);
cout<<"init thread exit"<<endl;
//pthread_exit(NULL);
}
void* thread1(void *var)
{
// pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
if(flag==2)
pthread_cond_signal(&cond);
cout<<"this is thread1"<<endl;
flag=1;
pthread_mutex_unlock(&mutex);
pthread_join(*(pthread_t *)var,NULL);
cout<<"thread1 exit"<<endl;
}
void* thread2(void *var)
{
// pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
if(flag==1)
pthread_cond_signal(&cond);
cout<<"this is thread2"<<endl;
flag=2;
pthread_mutex_unlock(&mutex);
cout<<"thread2 exit"<<endl;
}
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <windows.h>
DWORD WINAPI ThreadProc(LPVOID);
DWORD WINAPI ThreadProc(LPVOID p) {
for (;;) {
puts("In ThreadProc()");
Sleep(100);
}
return 100;
}
int main() {
HANDLE hThread;
DWORD dwThId;
hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThId);
if (hThread) {
puts("start thread");
CloseHandle(hThread);
}
ExitThread(2);
assert(FALSE);
return EXIT_SUCCESS;
}
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <windows.h>
DWORD WINAPI ThreadProc(LPVOID);
DWORD WINAPI ThreadProc(LPVOID p) {
for (;;) {
puts("In ThreadProc()");
Sleep(100);
}
return 100;
}
int main() {
HANDLE hThread;
DWORD dwThId;
hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThId);
if (hThread) {
puts("start thread");
CloseHandle(hThread);
}
ExitThread(2);
assert(FALSE);
return EXIT_SUCCESS;
}
[/quote]