Linux作业 线程 pthread

#include<stdio.h>
#include<pthread.h>
static pthread_mutex_t testlock;
pthread_t test_thread; 

void *test() {  
    pthread_mutex_lock(&testlock);     //阻塞式锁定互斥量testlock,如果互斥锁testlock已被另一个线程锁定和拥有,则调用线程test将阻塞,直到互斥锁testlock被解锁之后才可执行
    printf("thread Test() \n");     
    pthread_mutex_unlock(&testlock);      //解锁互斥量testlock的test函数
}

int main()
{  
    pthread_mutex_init(&testlock, NULL);     //初始化互斥量testlock,互斥量名为testlock,NULL表示为默认属性
    pthread_mutex_lock(&testlock);      
    printf("Main lock \n");     
    pthread_create(&test_thread, NULL, test, NULL);  //创建线程,并开始执行tese线程函数。ID为test_thread,NULL表示线程属性为默认属性,执行线程函数test,第二个人NULL表示无执行函数的传递参数
    sleep(1);    
    printf("Main unlock \n");     
    pthread_mutex_unlock(&testlock);      
    sleep(1);     
    pthread_join(test_thread,NULL);    //阻塞等待test_thread线程结束,结束时被等待线程test_thread资源被释放,NULL表示等待线程的返回值
    pthread_mutex_destroy(&testlock);      
    return 0;  
}

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/80209067