#include<iostream>
#include <unistd.h>
#include <cstring>
pthread_t thread [2];
pthread_mutex_t mut;
int num=0;
void* thread1(void *args){
printf("hi,I am thread1\n");
for (int i = 0; i <6 ; ++i) {
pthread_mutex_lock(&mut);
printf("[thread1]num=%d,i=%d\n",num,i);
num++;
pthread_mutex_unlock(&mut);
// sleep(2);
}
pthread_exit(NULL);
}
void* thread2(void *args){
printf("hi, I am thread2\n");
for (int i = 0; i <10 ; ++i) {
pthread_mutex_lock(&mut);
printf("[thread2]num=%d,i=%d\n",num,i);
num++;
pthread_mutex_unlock(&mut);
// sleep(3);
}
pthread_exit(NULL);
}
void thread_create(){
memset(&thread,0, sizeof(thread));
if (0!=pthread_create(&thread[0],NULL,thread1,NULL))
printf("thread1 create failure\n");
else
printf("thread1 established\n");
if(0!=pthread_create(&thread[1],NULL,thread2,NULL))
printf("thread2 create failure\n");
else
printf("thread2 established\n");
}
void thread_wait(){
if(0!=thread[0]){
pthread_join(thread[0],NULL);
printf("thread 1 is over\n");
}
if(0!=thread[1]){
pthread_join(thread[1],NULL);
printf("thread 2 is over\n");
}
}
int main(){
pthread_mutex_init(&mut,NULL);
printf("main thread:creating threads...\n");
thread_create();
printf("main thread:waiting threads to accomplish task ...\n");
thread_wait();
return 0;
}
这里,我时用liunx下,CmakeLists.txt 进行配置文件;
cmake_minimum_required(VERSION 3.9) project(code) set(CMAKE_CXX_STANDARD 11) add_executable(code code/main.cpp) target_link_libraries(code pthread)如果不
target_link_libraries(code pthread)
会出现的错误为:
CMakeFiles/code.dir/code/main.cpp.o:在函数‘thread_create()’中:
/home/shenying/code/code/main.cpp:34:对‘pthread_create’未定义的引用
/home/shenying/code/code/main.cpp:38:对‘pthread_create’未定义的引用
CMakeFiles/code.dir/code/main.cpp.o:在函数‘thread_wait()’中:
/home/shenying/code/code/main.cpp:45:对‘pthread_join’未定义的引用
/home/shenying/code/code/main.cpp:49:对‘pthread_join’未定义的引用
collect2: error: ld returned 1 exit status
CMakeFiles/code.dir/build.make:94: recipe for target 'code' failed
make[3]: *** [code] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/code.dir/all' failed
make[2]: *** [CMakeFiles/code.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/code.dir/rule' failed
make[1]: *** [CMakeFiles/code.dir/rule] Error 2