@rg070836rg
2015-11-13T10:22:35.000000Z
字数 1290
阅读 1217
未分类
#include"stdlib.h"
#include"stdio.h"
#include"time.h"
#include"sched.h"
#include"linux/sem.h"
#include"errno.h"
#define NCNT 10
#define INIT_BANK 10000
#define STACK_FRAME 8192
void* ThreadProc(int* arg);
long account[NCNT];
unsigned long ntrans;
int main()
{
int nRetCode = 0;
int i;
int clone_flag;
int arg[NCNT];
char *stack[NCNT], *st[NCNT];
char ch;
ntrans = 0;
clone_flag = CLONE_VM|CLONE_SIGHAND|CLONE_FS|CLONE_FILES;
for(i=0; i<NCNT; i++)
{
arg[i] = i;
account[i] = INIT_BANK;
}
for(i=0; i<NCNT; i++)
{
st[i] = (char*)malloc(STACK_FRAME);
stack[i] = st[i]+STACK_FRAME;
clone((void*)ThreadProc, stack[i], clone_flag, &arg[i]);
}
for(i=0; i<NCNT; i++)
free(st[i]);
while((ch = getchar())! = 'c')
return nRetCode;
}
void test()
{
int i;
long sum = 0;
for(i=0; i<NCNT; i++) sum += account[i];
printf("trans=%ld sum=%ld\n", ntrans, sum);
for(i=0; i<NCNT; i++)
printf("[%2d]=%5ld/n", i, account[i]);
printf("\n");
}
void transfer(int from, int to, int amount)
{
int t;
int i;
while(account[from] < amount) usleep(10000);
t = account[from];
t = t-amount;
account[from] = t;
t = account[to];
t = t+amount;
account[to] = t;
usleep(10);
ntrans++;
if(ntrans % 1000==0) test();
}
void* ThreadProc(int *arg)
{
int from;
from = *arg;
while(1)
{
srand((unsigned)time(NULL));
int to = (int)(NCNT*(rand()/(RAND_MAX+1, 0)));
if(to==NCNT) to = 0;
if(to==from) to = (to+1)%NCNT;
int amount = 1+(int)( (INIT_BANK*(rand()/(RAND_MAX+1, 0)))/2 );
transfer(from, to, amount);
}
return;
}