Untitled

 avatar
unknown
plain_text
4 years ago
2.0 kB
7
Indexable
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <string.h>

#define THREAD_COUNT 2
typedef struct global_data {
    int count;
    int number[THREAD_COUNT];
    int entering[THREAD_COUNT];
} global_data;
//??銝芰??global_data???銝波nt count


global_data gdata;

void lock(int thread)
{
	gdata.entering[thread]=1;
	int max_ticket=0;
	
	for(int i=0;i< THREAD_COUNT;++i){
		int ticket= gdata.number[i];
		max_ticket=ticket>max_ticket?ticket:max_ticket;
	}
	gdata.number[thread]=max_ticket+1;
	
	gdata.entering[thread]=0;
	
	for(int other=0;other<THREAD_COUNT;++other){
		while(gdata.entering[other]){
		}
		while(gdata.number[other]!=0&&(gdata.number[other]<gdata.number[thread]||(gdata.number[other]==gdata.number[thread]&&other<thread))){
		}
	}
	
	
	
	
	
}
void unlock(int thread){
	gdata.number[thread]=0;
}




void* subchild(void *arg) {  //?賒???
    
    int i = 0;
    long thread=(long)arg;
    
    do {
        // critical section
        lock(thread);
        gdata.count-=1;
        // ----------------
        printf("--sub = %d\n",gdata.count);
        i++;
        unlock(thread);
    }while(i < 99999);
}

void* addchild(void *arg) { //?賒???
    
    int i = 0;
    
	long thread=(long)arg;
    
    do{
        // critical section
        lock(thread);
        
        gdata.count+=1;
        // ----------------
        printf("++add = %d\n",gdata.count);
        i++;
        unlock(thread);
    }while(i<99999);
}

int main() {

	pthread_t t1, t2;
	
	memset((void*)gdata.number,0,sizeof(gdata.number));
	memset((void*)gdata.entering,0,sizeof(gdata.entering));
	gdata.count = 0;

	printf("START do SOME thing\n");

	pthread_create(&t1, NULL, subchild, (void*)((long)0));
	pthread_create(&t2, NULL, addchild, (void*)((long)1));//隡??餌??眠oid?€閬蓮敶X€?

	pthread_join(t1, NULL);
	pthread_join(t2, NULL);

	printf("global data = %d\n", gdata.count);

	return 0;
}
Editor is loading...