多线程示例

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值