C++互斥锁

    xiaoxiao2021-03-28  33

    #include<pthread.h> pthread_mutex_t abc;               //创建一个名为abc的semaphore变量; pthread_mutex_init(&abc,NULL) ;   //初始化     (第一个为互斥变量地址,第二个为互斥变量属性,NULL即为默认快速互斥锁,即abc=1) pthread_mutex_destroy(&abc)        //销毁锁 int pthread_mutex_lock(&abc)  ;   // P一下abc              成功返回0 int pthread_mutex_unlock(&abc)  ;   // V一下abc        成功返回0

     

    注意创建线程的那一瞬间继承前面的所有数据,之后线程与其他线程之间的数据就分开了

     

    未加锁版:

    #include<stdio.h> #include<pthread.h> using namespace std; int num=100; void* tprocess1(void* args) { while(num>0){ int i=num; printf("tprocess1--%d\n",i); i--; num=i; } return NULL; } void* tprocess2(void* args) { while(num>0){ int i=num; printf("tprocess2--%d\n",i); i--; num=i; } return NULL; } int main() { pthread_t t1; pthread_t t2; pthread_create(&t1,NULL,tprocess1,NULL); pthread_create(&t2,NULL,tprocess2,NULL); //注意这句开始的时候num可能已经不是为100了,假设为97,则tprocess2继承97往下输出 pthread_join(t1,NULL); pthread_join(t2,NULL); return 0; }

    加锁版:(规规矩矩的从100输出到0)

     

     

    #include<stdio.h> #include<pthread.h> using namespace std; pthread_mutex_t abc; int num=100; void* tprocess1(void* args) { while(num>0){ pthread_mutex_lock(&abc); int i=num; printf("tprocess1--%d\n",i); i--; num=i; pthread_mutex_unlock(&abc); } return NULL; } void* tprocess2(void* args) { while(num>0){ pthread_mutex_lock(&abc); int i=num; printf("tprocess2--%d\n",i); i--; num=i; pthread_mutex_unlock(&abc); } return NULL; } int main() { pthread_t t1; pthread_t t2; pthread_mutex_init(&abc,NULL); pthread_create(&t1,NULL,tprocess1,NULL); pthread_create(&t2,NULL,tprocess2,NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); pthread_mutex_destroy(&abc)  return 0; }

     

     

     

     

     

     
    转载请注明原文地址: https://ju.6miu.com/read-664752.html

    最新回复(0)