带锁的多线程。
Mutexes:
Mutexes are used to prevent data inconsistencies due to operations by
multiple
threads upon the same memory area performed at the same time or to
prevent race conditions where an order of operation upon the memory is
expected.
A contention or race condition often occurs when two or more threads
need to perform operations on the same
memory area, but the results of computations depends on
the order in which these operations are performed. Mutexes are used for
serializing shared resources such as memory. Anytime a global resource
is accessed by more
than one thread the resource should have a Mutex associated with it.
One can apply a mutex to protect a segment of memory ("critical region")
from other threads.
Mutexes can be applied only to threads in a single process and do not
work
between processes as do semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute functionC */
if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}
if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
Results:
Counter value: 1
Counter value: 2
When a mutex lock is attempted against a mutex which is held by another thread,
the thread is blocked until the mutex is unlocked.
When a thread terminates, the mutex does not unless explicitly unlocked.
Nothing happens by default.
分享到:
相关推荐
此文档能够让读者彻底了解JAVA开发中的多线程并发锁的使用
泛型单例父类(带锁线程可释放),很好用的一个泛型单例父类,想将一个类变成单例类的时候,只有继承这个...而且带线程锁,不怕多线程的时候出现错误了,而且还能手动释放;完全成品.cs文件,直接扔项目里就能用;好用的不得了;
如果多线程同时读写(这里的指不同的线程用使用的是不同的Helper实例),后面的就会遇到android.database.sqlite.SQLiteException: database is locked这样的异常。对于这样的问题,解决的办法就是keep single ...
带锁的多线程 牛头怪的生日派对 牛头怪邀请了N位客人参加他的生日聚会。 客人到来时,他宣布以下消息。 客人可以一次进入迷宫,只有在他邀请他们进入时才可以进入。 在迷宫的尽头,牛头怪将生日蛋糕放在盘子上。 当...
带锁的多线程 同步方式:细粒度 该模块的设计负责测量下一代Mars Rover的大气温度,配有多核CPU和8个温度传感器。 传感器负责定期收集温度读数并将其存储在共享的存储空间中。 大气温度模块必须在每个小时结束时编辑...
Windows7系统中,当设置某一个文件夹的属性为共享后,文件夹的图标上就增加了一个小锁图案,起到一个标记的作用。
从尺寸上讲,同步代码块比同步方法小。你可以把同步代码块看成是没上锁房间里的一块用带锁的屏风隔开的空间
魔改版bios,带锁频
走廊上n个带锁的门,从1到n一次编号,最初都关着,我们从门前经过n次,每次都从1号门开始,在第i次经过时,我们改变i的倍数的门锁状态,这样,最后一次经过时,那些门开着,那些门关着? 问题分析 首先举一个...
标准型带锁髓内钉.ppt
电子政务-带锁电源插座.zip
电子政务-带锁电源插头.zip
电子政务-带锁电视机.zip
行业资料-建筑装置-带锁皮面笔记本.zip
电子政务-带锁的防触电插座.zip
电子政务-带锁的电动定时器.zip
ORACLE如何杀掉带锁的进程.txt
电子政务-带锁装置的电视机.zip
电子政务-带锁卡电凝钳手柄.zip
行业资料-交通装置-一种带锁车轮钢圈.zip