您的位置:首页 > 编程语言 > C#

C#的多线程能力(Mutex的作用)

2009-09-15 14:48 295 查看
System.Threading.Mutex
:同步基元,它只向一个线程授予对共享资源的独占访问权。当有两个或两个以上的线程要对一个共享资源进行操作的时候,就要

System.Threading.Mutex
互斥体来进行调节。保证只有一个线程可以对共享资源进行控制。如果一个线程获得了互斥体,其他线程只能在第一个线程放弃互斥体之前先挂起。互斥体可以通过waitone()
请求相同的互斥体而不会阻塞其执行

但必须在使用后
ReleaseMutex

来释放互斥体。

下边是示例代码

using
System;

using
System.Collections.Generic;

using
System.Text;

using
System.Threading;

using
System.Collections;

namespace
ConsoleApplication19

{

class
Program

{

public
static
ArrayList
student = new
ArrayList
();

public
static
bool
flag = false
;

static
void
Main(string
[] args)

{

Thread
schooladd = new
Thread
(students
.Add);

schooladd.Start();

Thread
schoolreduce = new
Thread
(students
.Reduce);

schoolreduce.Start();

string
d = Console
.ReadLine();

}

}

class
students

{

public
static
System.Threading.Mutex
mutex = new
System.Threading.Mutex
(false
,null
/*"Program.student"*/
, out
Program
.flag);//null
是互斥体的名字可以是任何值

public
static
void
Add()

{

mutex.WaitOne();

Program
.student.Add(new
students
());

Console
.WriteLine("
现在学校里有{0}
:名学生"
, Program
.student.Count);

mutex.ReleaseMutex();

}

public
static
void
Reduce()

{

mutex.WaitOne();//
保证了在该线程没有ReleaseMutex
之前没有其他线程可以对Program.student
进行访问

Program
.student.RemoveAt(Program
.student.Count-1);

Console
.WriteLine("
现在学校里有{0}
:名学生"
, Program
.student.Count);

mutex.ReleaseMutex();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: