首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C关于线程的有关问题

2012-03-01 
C关于线程的问题#include stdio.h#include windows.h#include malloc.h/*线程的最大数*/#definestac

C关于线程的问题
#include "stdio.h"
#include <windows.h>
#include <malloc.h>
/*线程的最大数*/
#define stackSize 10

/*控制线程的结构体*/
struct operatThread{
/*begin为0,就是未开始,1就是已经开始了,*/
int begin;
/*stop为0就是运行中,1就是暂停*/
 int stop;
/*end为0就是未结束,1就是已经结束*/
int end;
/*权限1到10,10最大*/
int check;
/*运行时间*/
int time;
/*线程名*/
char * name;

DWORD dw;

};

//时间片线程函数
DWORD WINAPI ThreadProc(LPVOID * lpParam)
{ int i=0;
 struct operatThread * current=(struct operatThread *)lpParam;
 while(i<30){
 
 while(current->stop==1){
 Sleep(10);
 }
  printf("线程%s :%d\n",&current->name,i);
  i++;
 }
 
 
 current->end=1;
  printf("线程%s完结\n",&current->name);
 return 1;
}


/*下面是写栈*/
struct operatThread * operatThread[stackSize];


int stackI=0,stackJ=0;  


void put(struct operatThread * op){

  if(stackJ==stackSize)stackJ=0;
   
  operatThread[stackJ]=op;
stackJ++;  
}

struct operatThread * get(){
  if(stackI==stackJ)return NULL;
  return operatThread[stackI];
}

int getStackSize(){
  return stackJ-stackI;
}


void myremove(){
  if(stackI==stackSize)stackI=0;
  stackI++;
}

/*时间片轮法*/
void timeAttemper(){
  /*进程数*/
  int number=0;
  int i;
   
  struct operatThread * temp[stackSize];
  HANDLE hThread[stackSize];
 DWORD dwThreadId[stackSize];
   
   
  printf("输入你要产生的进程数:");
  scanf("%d",&number);
  getchar();
   
  while(number<0||number>stackSize){
  printf("你输入有误,请重新输入:");
  scanf("%d",&number);
  getchar();
  }
 
 
 for(i=0;i<number;i++){
 temp[i]=(struct operatThread *)malloc(sizeof(struct operatThread));
 temp[i]->begin=1;
 temp[i]->stop=1;
 temp[i]->end=0;
 
 printf("输入%d进程的名称:",i+1);
 scanf("%s",&temp[i]->name);
 
 getchar();
 
 //创建一个新线程

 hThread[i] = CreateThread(
  NULL, //默认安全属性
  NULL, //默认堆栈大小
  ThreadProc, //线程入口地址(执行线程的函数)
  temp[i], //传给函数的参数
  1, //指定线程立即执行
  &dwThreadId[i] //返回线程的ID号
  );
 temp[i]->dw=dwThreadId[i];

 put(temp[i]);
 }

 while(getStackSize()!=0){
 
 struct operatThread * current=get();

 current->stop=0;
Sleep(10);
 current->stop=1;

 myremove();
 if(current->end==0)
 put(current);
 }

 
for(i=0;i<number;i++)
 CloseHandle(hThread[i]);

}

void shoreTimeAttemper(){}
void dynamicAttemper(){}

main()
{

  /*选择边种算法*/
  int suanfaId=0;
  int i=0;
  
  printf("1,时间片轮法\n");
  printf("2,短时间作业法\n");
  printf("3,动态优先法\n");
  printf("输入你要演示的算法:");
  scanf("%d",&suanfaId);
  getchar();
   


  while(suanfaId<1||suanfaId>4){
  printf("你输入有误,请重新输入:");
  scanf("%d",&suanfaId);
  getchar();
  }
   
  if(suanfaId==1){
  timeAttemper();
  }
   
  else if(suanfaId==2){
  shoreTimeAttemper();
  }
   
  else {
  dynamicAttemper();
  }
}

为什么我把stop设置为1,不能把产生的线程暂停的????

[解决办法]
current-> stop=0; 
Sleep(10); 
current-> stop=1;
///////////////////////
这里sleep的时间足够把线程执行完了吧,等你设置1的时候线程估计已经退出了。 

热点排行