线程同步的办法有哪些 Linux下真现线程同步的三种办法

相关游戏 相关文章 发表评论字体大小:【 | |

作者:佚名 2020-01-06 来源:本站整理    浏览:9     评论:0 条

  线程异步的要领有哪些?正在linux高,体系提求了不少种体式格局去真现线程异步,此中最罕用的即是互斥锁、前提变质战疑号质那三种体式格局,否能另有不少搭档对付那三种要领皆没有相熟,上面便给各人具体引见高。

线程同步的办法有哪些 Linux下真现线程同步的三种办法

  Linux高真现线程异步的三种要领:

  1、互斥锁(mutex)

  经由过程锁机造真现线程间的异步。

  一、始初化锁。正在Linux高,线程的互斥质数据范例是pthread_mutex_t。正在运用前,要对它停止始初化。

  动态分配:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

  静态分配:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr);

  二、添锁。对同享资源的会见,要对互斥质停止添锁,若是互斥质曾经上了锁,挪用线程会梗阻,曲到互斥质被解锁。

  int pthread_mutex_lock(pthread_mutex *mutex);

  int pthread_mutex_trylock(pthread_mutex_t *mutex);

  三、解锁。正在完成为了对同享资源的会见后,要对互斥质停止解锁。

  int pthread_mutex_unlock(pthread_mutex_t *mutex);

  4、销誉锁。锁正在是运用完成后,须要停止销誉以开释资源。

  int pthread_mutex_destroy(pthread_mutex *mutex);

01#include <cstdio>02#include <cstdlib>03#include <unistd.h>04#include <pthread.h>05#include "iostream"06using namespace std;07pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;08int tmp;09void* thread(void *arg)10{11cout << "thread id is " << pthread_self() << endl;12pthread_mutex_lock(&mutex);13tmp = 12;14cout << "Now a is " << tmp << endl;15pthread_mutex_unlock(&mutex);16return NULL;17}18int main()19{20pthread_t id;21cout << "main thread id is " << pthread_self() << endl;22tmp = 3;23cout << "In main func tmp = " << tmp << endl;24if (!pthread_create(&id, NULL, thread, NULL))25{26cout << "Create thread success!" << endl;27}28else29{30cout << "Create thread failed!" << endl;31}32pthread_join(id, NULL);33pthread_mutex_destroy(&mutex);34return 0;35}36//编译:g++ -o thread testthread.cpp -lpthread复造代码#include <cstdio>#include <cstdlib>#include <unistd.h>#include <pthread.h>#include "iostream"using namespace std;pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;int tmp;void* thread(void *arg){cout << "thread id is " << pthread_self() << endl;pthread_mutex_lock(&mutex);tmp = 12;cout << "Now a is " << tmp << endl;pthread_mutex_unlock(&mutex);return NULL;}int main(){pthread_t id;cout << "main thread id is " << pthread_self() << endl;tmp = 3;cout << "In main func tmp = " << tmp << endl;if (!pthread_create(&id, NULL, thread, NULL)){cout << "Create thread success!" << endl;}else{cout << "Create thread failed!" << endl;}pthread_join(id, NULL);pthread_mutex_destroy(&mutex);return 0;}//编译:g++ -o thread testthread.cpp -lpthread

这些是你想要的吗?

相关游戏

网友评论

评论需审核后才能显示