编写一个多线程程序,使得3个线程同时运行。

linux 编写一个多线程程序,要求主线程创建3个子线程,3个子线程在执行时都修改一个他们的共享变量。~

void func1(int n)
{
printf("%d",n*10);
}
void func1(int n)
{
printf("%d",n-10);
}

void func1(int n)
{
printf("%d",n/2);
}

int main(void)
{
int n = 10;
pthread_t 1_thread,2_thread,3_thread;
pthread_create(1_thread,NULL,func1,n);
pthread_create(2_thread,NULL,func2,n);
pthread_create(3_thread,NULL,func3,n);
return 0;
}

DWORD WINAPI ThreadProc1( LPVOID lpvUser )
{

for( int i = 0; i < 5; i++ )
{
Sleep( 1 );//added.
cout<<"1"<<endl;
}

return 0;
}

DWORD WINAPI ThreadProc( LPVOID lpvUser )
{

for( int i = 0; i < 5; i++ )
{
Sleep( 1 );//added.
cout<<"2"<<endl;
}

return 0;
}

说实话,实现这个是没有意义的,多线程的并发主要是通过同步手段来实现的。同步的内核对象例如,临界区、信号量和互斥量,等。一般是用来对共享资源的保护。所以,干这种事没有意义,可能您想模拟时间片轮询,当然可以,对于线程默认创建的优先级都是一样的,所以他们确实是按照时间片轮询的方式调度的。为什么,不能输出你想要的结果呢?是因为一个时间片长足以让你的语句输出多次了。

才给5分啊~~~~~~难怪大家懒得做。我就贴一下读写者问题的多线程程序吧,希望对你有帮助。(好像是2个线程,太久了懒得看)
#include "windows.h"
#include <conio.h>
#include <stdlib.h>
#include <fstream.h>
#include <io.h>
#include <string.h>
#include <stdio.h>

#define READER 'R' //读者
#define WRITER 'W' //写者
#define INTE_PER_SEC 1000 //每秒时钟中断次数
#define MAX_THREAD_NUM 64 //最大线程数目
#define MAX_FILE_NUM 32 //最大数据文件数目
#define MAX_STR_LEN 32 //字符串长度

int readcount=0; //读者数目 (属临界资源,需以互斥方式访问)
int writecount=0; //写者数目 (属临界资源,需以互斥方式访问)
//定义3个临界资源

CRITICAL_SECTION RP_Write; //临界区控制变量 (用于读者优先)
CRITICAL_SECTION cs_Write; //临界区控制变量 (用于写者优先)
CRITICAL_SECTION cs_Read; //临界区控制变量 (用于写者优先)
//定义线程及其操作行为信息结构

struct ThreadInfo
{
int serial; //线程序号
char entity; //线程类别(是读者还是写者)
double delay; //线程延迟
double persist; //线程读写操作的持续时间
};

// 读者优先――读者线程
void RP_ReaderThread(void *p) //p: 读者线程信息
{
//互斥变量
HANDLE h_Mutex;
h_Mutex = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex_for_readcount");
//从参数中获得信息
DWORD wait_for_mutex; //等待互斥变量所有权
DWORD m_delay; //延迟时间
DWORD m_persist; //读文件持续时间
int m_serial; //线程序号

m_serial = ((ThreadInfo*)(p))->serial;
m_delay = (DWORD)((ThreadInfo*)(p))->delay*INTE_PER_SEC;
m_persist = (DWORD)((ThreadInfo*)(p))->persist*INTE_PER_SEC;
Sleep(m_delay); //延迟等待
//输出读进程已发出读请求的提示信息
printf ("Reader thread %d sends the reading require.\n", m_serial);

//等待互斥信号,保证对readcount的互斥访问
wait_for_mutex = WaitForSingleObject(h_Mutex,-1);
readcount++;
if (readcount==1) //第一个读者,等待临界区资源
EnterCriticalSection(&RP_Write);
ReleaseMutex(h_Mutex); //释放互斥信号
//输出读进程I 正在临界区中读操作的提示信息
printf("Reader thread %d begins to read file.\n", m_serial);
Sleep(m_persist);
//退出线程
printf("Reader thread %d finished reading file. \n",m_serial);
//等待互斥信号,保证对readcount的互斥访问
wait_for_mutex = WaitForSingleObject(h_Mutex,-1);
readcount--;
if (readcount==0) LeaveCriticalSection(&RP_Write);
ReleaseMutex(h_Mutex); //释放互斥信号
}

// 读者优先――写者线程
void RP_WriterThread(void *p) //p: 写者线程信息
{
DWORD m_delay; //延迟时间
DWORD m_persist; //读文件持续时间
int m_serial; //线程序号
//从参数中获取信息m_serial, m_delay, m_persist ,
m_serial = ((ThreadInfo*)(p))->serial;
m_delay = (DWORD)((ThreadInfo*)(p))->delay*INTE_PER_SEC;
m_persist = (DWORD)((ThreadInfo*)(p))->persist*INTE_PER_SEC;

//延迟等待m_delay秒;
Sleep(m_delay);
//输出信息"写线程 %d 发出写请求;
printf ("Writer thread %d sends the writing require.\n", m_serial);
//等待临界资源
EnterCriticalSection(&RP_Write);
//输出正在临界区执行写操作的提示信息
//在临界区中写操作,至少持续m_persist秒钟
printf("Writer thread %d begins to write file.\n", m_serial);
Sleep(m_persist);
printf("Writer thread %d finished writing file. \n",m_serial);
//释放临界资源
LeaveCriticalSection(&RP_Write);
}

// 读者优先――处理函数
void ReaderPriority(char *file) //file: 文件名
{
DWORD n_thread=0; //保存线程数目变量
DWORD thread_ID; //线程ID
DWORD wait_for_all; //保存――等待所有线程结束的返回值――的变量
HANDLE h_Thread[MAX_THREAD_NUM];
ThreadInfo thread_info[MAX_THREAD_NUM];
HANDLE h_Mutex=CreateMutex(NULL,FALSE,"mutex_for_readcount");

readcount=0;
InitializeCriticalSection(&RP_Write); //初始化临界区
ifstream inFile;
inFile.open(file);
printf("Reader Priority :\n\n");

while (inFile) { //读入每个读者、写者的信息
inFile>>thread_info[n_thread].serial;
inFile>>thread_info[n_thread].entity;
inFile>>thread_info[n_thread].delay;
inFile>>thread_info[n_thread].persist;
inFile.get();
n_thread++;
}
n_thread--; //modify
for(int j=0;j<(int)(n_thread); j++){
cout<<"threadinfo["<<j<<"]="<<thread_info[j].serial<<","<<thread_info[j].entity
<<","<<thread_info[j].delay<<","<<thread_info[j].persist<<endl;
}
for(int i=0; i<(int)(n_thread); i++){
//创建一个不被子进程继承的,使用默认大小堆栈的线程
if( thread_info[i].entity ==READER || thread_info[i].entity=='r')
h_Thread[i] = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)(RP_ReaderThread),
&thread_info[i],0,&thread_ID);
// thread_info[i]籍此传递给被创建线程,
// 创建标志=0, 表示线程被创建后立即执行 (其它:CREATE_SUSPEND)
//thread_ID 存放放回的线程ID标识, 可不用
else
h_Thread[i]=CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)(RP_WriterThread),
&thread_info[i],0,&thread_ID);
}
//等待所有的线程结束
wait_for_all = WaitForMultipleObjects(n_thread, h_Thread, TRUE, -1);
printf("All reader and writer have finished operating. \n");
}

// 写者优先――读者线程
void WP_ReaderThread(void *p) //p: 读者线程信息
{
DWORD m_delay; //延迟时间
DWORD m_persist; //读文件持续时间
int m_serial; //线程序号

m_serial = ((ThreadInfo*)(p))->serial;
m_delay = (DWORD)((ThreadInfo*)(p))->delay*INTE_PER_SEC;
m_persist = (DWORD)((ThreadInfo*)(p))->persist*INTE_PER_SEC;
Sleep(m_delay);
printf ("Reader thread %d sends the reading require.\n", m_serial);
//延迟等待
//从参数中获取信息m_serial, m_delay, m_persist ,
//延迟等待m_delay秒;
//输出信息"读线程 %d 发出读请求的提示信息;

//打开(获取)两个互斥变量
HANDLE h_Mutex1, h_Mutex2;
h_Mutex1=OpenMutex(MUTEX_ALL_ACCESS, FALSE, "mutex_for_writecount1");
/*由于写者优先,即使临界区中已有读者,也不能马上进入,
要等到没有等待写者(在写进程中,当无等待写者释放读者临界区所有权cs_Read)
因此,这里需要一个互斥信号量附加控制读者进入过程,这在读者优先算法中是不需要的。*/

DWORD wait_for_mutex1=WaitForSingleObject(h_Mutex1,-1);
EnterCriticalSection(&cs_Read);
// 用h_mutex2控制对readcount的访问
h_Mutex2 = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex_for_readcount2");
DWORD wait_for_mutex2 = WaitForSingleObject(h_Mutex2,-1);
readcount++;
if ( readcount==1) //第一个读者要等待写者写完
EnterCriticalSection(&cs_Write);
ReleaseMutex(h_Mutex2);

LeaveCriticalSection(&cs_Read); //让其它读者可进入临界区
ReleaseMutex(h_Mutex1);
//输出某读者进程在临界区中读的信息;
//在临界区中读操作,至少持续m_persist秒钟
//输出某读者进程退出临界区的信息;
printf("Reader thread %d begins to read file.\n", m_serial);
Sleep(m_persist);
//退出线程
printf("Reader thread %d finished reading file. \n",m_serial);
wait_for_mutex2 = WaitForSingleObject(h_Mutex2,-1);
readcount--;
if ( readcount==0) //最后一个读者,要唤醒写者
LeaveCriticalSection(&cs_Write);
ReleaseMutex(h_Mutex2);
}

// 写者优先――写者线程
void WP_WriterThread(void *p) //p: 写者线程信息
{
DWORD m_delay; //延迟时间
DWORD m_persist; //读文件持续时间
int m_serial; //线程序号
//从参数中获取信息m_serial, m_delay, m_persist ,
m_serial = ((ThreadInfo*)(p))->serial;
m_delay = (DWORD)((ThreadInfo*)(p))->delay*INTE_PER_SEC;
m_persist = (DWORD)((ThreadInfo*)(p))->persist*INTE_PER_SEC;

//延迟等待m_delay秒;
Sleep(m_delay);
//输出信息"写线程 %d 发出写请求;
printf ("Writer thread %d sends the writing require.\n", m_serial);
//打开(获取)两个互斥变量h_Mutex3
HANDLE h_Mutex3;
h_Mutex3 = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex_for_writecount3");
DWORD wait_for_mutex3 = WaitForSingleObject(h_Mutex3,-1);
writecount++;
if (writecount==1) //第一个等待写者,等待读者读完
EnterCriticalSection(&cs_Read);
ReleaseMutex(h_Mutex3);

EnterCriticalSection(&cs_Write);
//进入写着临界区
//输出某写者进程在临界区中写的信息;
//至少持续m_persist秒钟
//输出某写者进程退出临界区的信息;
printf("Writer thread %d begins to write file.\n", m_serial);
Sleep(m_persist);
printf("Writer thread %d finished writing file. \n",m_serial);

LeaveCriticalSection(&cs_Write); //写者离开临界区
wait_for_mutex3 = WaitForSingleObject(h_Mutex3,-1);
writecount--;
if (writecount==0) //无其它等待写者,唤醒第一个读者
LeaveCriticalSection(&cs_Read);
ReleaseMutex(h_Mutex3);
}

// 写者优先――处理函数
void WriterPriority(char *file) //file: 文件名
{
DWORD n_thread=0, thread_ID, wait_for_all;
HANDLE h_Mutex1=CreateMutex(NULL,FALSE,"mutex_for_writecount1");
HANDLE h_Mutex2=CreateMutex(NULL,FALSE,"mutex_for_readcount2");
HANDLE h_Mutex3=CreateMutex(NULL,FALSE,"mutex_for_writecount3");
//用CreateMutex创建3个互斥信号量句柄h_mutex1,h_mutex2, h_mutex3;
//从数据文件读入信息,创建指定数目的读写进程
//读进程处理函数 WP_ReaderThread, 写进程处理函数WP_writerThread
HANDLE h_Thread[MAX_THREAD_NUM];
ThreadInfo thread_info[MAX_THREAD_NUM];
writecount=0;
readcount=0;
InitializeCriticalSection(&cs_Write);
InitializeCriticalSection(&cs_Read);
//初始化临界区
ifstream inFile;
inFile.open(file);
printf("Write Priority :\n\n");

while (inFile) { //读入每个读者、写者的信息
inFile>>thread_info[n_thread].serial;
inFile>>thread_info[n_thread].entity;
inFile>>thread_info[n_thread].delay;
inFile>>thread_info[n_thread].persist;
inFile.get();
n_thread++;
}
n_thread--;
for(int j=0;j<(int)(n_thread); j++){
cout<<"threadinfo["<<j<<"]="<<thread_info[j].serial<<","<<thread_info[j].entity
<<","<<thread_info[j].delay<<","<<thread_info[j].persist<<endl;
}
for(int i=0; i<(int)(n_thread); i++) {
//创建一个不被子进程继承的,使用默认大小堆栈的线程
if( thread_info[i].entity ==READER || thread_info[i].entity=='r' )
h_Thread[i] = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)(WP_ReaderThread),
&thread_info[i],0,&thread_ID);
// thread_info[i]籍此传递给被创建线程,
// 创建标志=0, 表示线程被创建后立即执行 (其它:CREATE_SUSPEND)
//thread_ID 存放放回的线程ID标识, 可不用
else
h_Thread[i]=CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)(WP_WriterThread),
&thread_info[i],0,&thread_ID);
}
//等待所有的线程结束
wait_for_all = WaitForMultipleObjects(n_thread, h_Thread, TRUE, -1);
printf("All reader and writer have finished operating. \n");
}

///////////////////////////////////////////////////////////
///主函数
int main(int argc, char** argv)
{
char ch;
while (true)
{
//打印显示信息
printf("***************************************\n");
printf(" 1. Reader Priority \n");
printf(" 2. Writer Priority \n");
printf(" 3. Exit \n");
printf("***************************************\n");
printf("Enter your choice(1,2,or 3): \n");
do {
ch = (char)_getch();
} while (ch != '1' && ch != '2' && ch!='3');
system("cls");
if(ch=='3') return 0;
else if(ch=='1') ReaderPriority("thread.dat");
else if(ch=='2') WriterPriority("thread.dat");
//结束
printf("\nPress any key to continute:");
_getch();
system("cls");
}
return 1;
}

3个线程同时写一个文件, 第一个写入A,第二个写入B,第三个C,如何保证文 ...
答:线程A author Administrator / private static final class A extends Thread{ private List<String> list;public A(List<String> list){ this.list = list;} Override public void run() { for(int i=0; i<30; i+=3){ list.add(i, "A");// 将B和C线程输出的地方占位 list.add(i+...

java多线程问题:模拟10个人在3个窗口买票的过程
答:synchronized (s)的s是synchronized 的参数,synchronized 的参数可以是任意对象,我定义了一个String类型的对象s,方便看程序而已。但是要注意,s的定义一定要在run方法之外,不然还会出现负数。因为你启动了3个线程,每个线程都调用了run方法,在每个线程就会在run方法里边产生自己的s对象,一共会产生3个...

JAVA多线程问题
答:2.编写3个线程,一个线程给某个对象里的整型变量赋初值,第二个线程给初值加10,第三个线程给变量值清0,要求这3个线程严格按照赋初值、加10、清0顺序执行,使用多线程的共享与同步的方式实现。/ public class ThreeThreadBaidu { public static void main(String[] args) { Myobject mo = new ...

如何创建和启动一个线程
答:1、设计一个线程,产生三个线程对象,设置三个线程的休眠时间,10s,20s,30s。主要采用Thread类,Runable接口。2、thread类是java.lang包中定义的,一个类只要继承Thread类,此类就是多线程操作类使用Threa类实现。3、测试运行结果。4、使用runnable接口实现,类中没有线程名称字段,所以建立一个name属性...

java 一个线程处理多个任务
答:多线程将多任务的思想拓展到应用,因此,您可以将单个应用中的特定步骤进一步分解成一个个线程,每个线程可以并行运行。操作系统不仅在不同的应用任务间分配处理时间,而且在一项应用的每个线程间分配处理时间。工程与科学方面的应用程序通常运行于专用的系统(可能没有多任务化)。而一个多线程NI LabVIEW程序...

Python编写程序,输入3个不重复的1位正整数,输出所有能用这3个1位正...
答:将三个数字组成一个序列 seq = [a, b, c]使用 permutations 函数获取所有长度为 3 的排列组合 perms = itertools.permutations(seq, 3)遍历所有排列组合,将每个组合转化为整数并输出 for perm in perms:num = perm[0] * 100 + perm[1] * 10 + perm[2]print(num)该程序会首先让用户输入...

3. 编制一个多线程程序,实现如下要求: ● 每隔1秒显示时间 ● 每隔2...
答:在main方法里同时执行两个线程,把你需要的信息在run()方法里写就可以了 Thread t1=new Thread(){ public void run(){ System.out.println("子线程1");} };//开启线程1 t1.start();Thread t2=new Thread(){ public void run(){ try { } catch (InterruptedException e) { e.print...

线程什么意思
答:什么是多线程? 多线程是为了使得多个线程并行的工作以完成多项任务,以提高系统的效率。线程是在同一时间需要完成多项任务的时候被实现的。 使用线程的好处有以下几点: ・使用线程可以把占据长时间的程序中的任务放到后台去处理 ・用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以...

基础Java题 试编写一个多线程的程序:启动4个线程。其中两个循环10次...
答:+ (i + 1) + ":\t");}for (Thread thread : trr) {thread.start();}for (Thread thread : trr) {thread.join();}System.out.println("所有线程结束查看结果:" + rec.getCount());}}class NumberTest implements Runnable {private Recoun re;private int n;NumberTest(Recoun r,...

编写一个程序(包括三个函数main,max,min),求三个数中的最大数和最小数...
答:int max(int a,int b,int c){ int zemp=a>b?a:b; //取得a,b中大的数 return zemp>c:zemp:c; //zemp 在和c比较 大的就是3个数中最大的}int min(int a,int b,int c){ int zemp=a<b?a:b; //取得a,b中小的数 return zemp<c:zemp:c; //zemp 在...

IT评价网,数码产品家用电器电子设备等点评来自于网友使用感受交流,不对其内容作任何保证

联系反馈
Copyright© IT评价网