亂貼小站公告欄

Easy_run_class v1.0.3 歡迎下載 (2011.10.04)

 
主要對象:JAVA 程式語言的初學者 (Windows XP / Vista / 7 適用)。

 
主要功能:
1.自動幫忙設定 JDK 的相關環境。
2.為副檔名為 .java 的檔案提供右鍵選單可直接【編譯並執行】。
3.為副檔名為 .class 的檔案提供雙擊即可快速執行的功能。

 
歡迎大家多多推廣。若有任何使用上的問題均可在此站留言。

在這篇主要是想要來分享自己的一個習慣

Notepad++ 的 Nppexec 可以對目前編輯的檔案,執行你腳本所定義的事情

於是,我就希望 Nppexec 也可以快速的察看 PHP 的執行結果

但是研究了 Nppexec 的說明文件之後

發現必須要寫一隻小程式,才能夠達到我的要求

( 也就是按了 Ctrl + F6 之後,我的預設瀏覽器,可以開啟該網頁 )

( http://127.0.0.1/...... )

現在來分享給大家我的作法。

首先,先簡介一下,我使用的環境是 ( Windows 7 + Appserv 2.6.0 )

我是把我自己的電腦當作測試伺服器使用,網頁寫好才放到正式伺服器

在 Notepad++ 裡面安裝了 Nppexec 之後,按下 F6,貼入以下指令

NPP_CONSOLE ?
npp_save
set PHP_www = D:\Dropbox\wwwhtml\
set PHP_url = http://127.0.0.1/
set PHP_open = D:\Dropbox\Public\program\NppExecPHPopen.exe
cmd.exe /c ""$(PHP_open)" "$(PHP_www)\" "$(PHP_url)" "$(FULL_CURRENT_PATH)""

簡單說明一下這段代碼

NPP_CONSOLE ?

這個是保留目前 Notepad++ 的 CONSOLE 開啟狀態,因為 CONSOLE 對 PHP 沒用

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

照這樣來說,我真的一個朋友也沒有.... 未來會不會有...未知數

‎[轉] 殺人後一個孩子的做法…不看你會後悔的…
有個男孩17~18歲,家裡很有錢,整天在外面和他的朋友們吃啊,喝啊,打架。
有一天他的父親問他:“你有多少朋友”
男孩回答:“我有好多”
父親:“那你照我說的去做,先在你的白襯衫上灑點雞血,然後拿去找你的朋友說你殺人了,看看他們的反映”
男孩照這父親的話做了,去找他認為最要好的朋友,找到第一個朋友。
朋友1:“你這是怎麼了,一身血”
男孩:“兄弟,我殺人了,借點錢給我,讓我到外面躲一躲行嗎。?”
朋友1:“最近家裡的手頭實在是有點緊沒錢,要不你去找別人問問。”
男孩失望的離開了,去找他認為第二個最好的朋友。
砰砰砰~~
朋友2透過門說:“誰啊”
男孩:“是我”
依然沒有開門:“什麼事啊”
男孩:“兄弟,我殺人了,借點錢給我,讓我到外面躲一躲行嗎。?”
朋友2和第一個朋友說的一樣的話。男孩很是惱火,這個竟然連門都不開的拒絶了。
他找遍了所有的朋友都被拒絶了。
他沮喪的回到了家,向父親說明了一切。
父親:“你去找我這一個半的朋友,先去找我這半個朋友”

Posted by 和風信使 at 痞客邦 PIXNET 留言(2) 引用(0) 人氣()

昨天,曾經是在聯大互相砥礪的吳秉綸來到中興來看我~
抱歉,鬧得有點不愉快
我不希望 我們的友誼之間 出現銅臭味
沒辦法啊= =
我真的對多層次傳銷印象太差了
簡單說,他就是在賣友誼
對我這種已經幾乎沒什麼朋友的人而言
我是承受不起的

1.從經濟層面上看
我目前已經有三個門號的手機了,我已經無力負擔再加一支的月租費
每個月要3、4百左右的月租費,我根本負擔不起

2.從多層次傳銷的印象
聽那個人介紹的時候,我都已經來聽了
你還要擺出一副你想聽我才願意講的感覺
然後還一直狂問說我到底想不想聽
這個舉動在我看來,就是你也對這個東西沒有自信
而且來弄得我心裡一肚子火
況且,我之前就從九把刀的網誌上面

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

在我認識的許多資訊人當中

很多人的 Linux 真的就都是學鳥哥出身

我自己也不例外

說真的 還蠻佩服他當初肯花這麼多時間來整理這些資料

但是,現在卻越來越看到越多

鳥哥網站上面的缺點

主要可以歸類成兩項:

1.臨時想要用的時候派不上用場

不知道大多數人第一次跟著學鳥哥

都是在什麼樣的年齡階段

像我,我雖然有先自學,但是只有去看有興趣的

在大學所上的 Unix 課程中,才真的整個學一遍

但是,不知道該說是鳥哥資安觀念很好

還是鳥哥【一朝被蛇咬,十年怕草蛇】

每次上課時,鳥哥的網站總是派不上用場

歸咎原因,是因為電腦教室對外 IP 都相同

然後就被伺服器判定為攻擊

所以就連不上啦@@

想必很多跟我一樣的大學生

每次在上 Unix 課程時

, , , , ,

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

/*
    mkfifo fifo1
    mkfifo fifo2
    echo "test" > fifo1
*/
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/select.h>
#include<limits.h>
#include<unistd.h>
#include<fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    char buffer[PIPE_BUF];
    int fd1 = open("fifo1",O_RDWR | O_NONBLOCK);
    int fd2 = open("fifo2",O_RDWR | O_NONBLOCK);
    int maxfd=fd1;
    if(maxfd<fd2)maxfd=fd2;
    maxfd++;
    printf("fd1=%d, fd2=%d, maxfd=%d",fd1,fd2,maxfd);
    fd_set fdSet;
    struct timeval tv;
    
    while(1)
    {
        FD_ZERO(&fdSet);
        tv.tv_sec=3;
        tv.tv_usec=0;
        FD_SET(fd1,&fdSet);
        FD_SET(fd2,&fdSet);
        memset(buffer,0,sizeof(buffer));
        int ready=select(maxfd,&fdSet,NULL,NULL,&tv);
        if(ready==-1)
        {
            printf("failure\n");
            continue;
        }
        if(ready==0)
        {
            printf("Timeout\n");
            continue;
        }
        if(FD_ISSET(fd1,&fdSet))
        {
            read(fd1,&buffer,sizeof(buffer));
            printf("Device 1: %s\n",buffer);
        }
        if(FD_ISSET(fd2,&fdSet))
        {
            read(fd2,&buffer,sizeof(buffer));
            printf("Device 2: %s\n",buffer);
        }
    }
    close(fd1);
    close(fd2);
}

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

轉自:http://60.248.128.85/bbs/dv_rss.asp?s=xhtml&boardid=63&id=491&page=3

這是一篇程式員寫給程式員的趣味讀物。所謂趣味是指可以比較輕鬆地瞭解一些原來不清楚的概念,增進知識,類似於打RPG遊戲的升級。整理這篇文章的動機是兩個問題:

問題一:

使用Windows記事本的「另存為」,可以在GBK、Unicode、Unicode big endian和UTF-8這幾種編碼方式間相互轉換。同樣是txt文件,Windows是怎樣辨識編碼方式的呢?

我很早前就發現Unicode、Unicode big endian和UTF-8編碼的txt文件的開頭會多出幾個字元,分別是FF、FE(Unicode),FE、FF(Unicode big endian),EF、BB、BF(UTF-8)。但這些標記是基於什麼標準呢?

問題二:
最近在網上看到一個ConvertUTF.c,達到了UTF-32、UTF-16和UTF-8這三種編碼方式的相互轉換。對於Unicode(UCS2)、GBK、UTF-8這些編碼方式,我原來就瞭解。但這個程式讓我有些糊塗,想不起來UTF-16和UCS2有什麼關係。

查了查相關資料,總算將這些問題弄清楚了,順帶也瞭解了一些Unicode的細節。寫成一篇文章,送給有過類似疑問的朋友。本文在寫作時盡量做到通俗易懂,但要求讀者知道什麼是字元,什麼是十六進制。

0、big endian和little endian

big endian和little endian是CPU處理多字元數的不同方式。例如「漢」字的Unicode編碼是6C49。那麼寫到文件裡時,究竟是將6C寫在前面,還是將49寫在前面?如果將6C寫在前面,就是big endian。還是將49寫在前面,就是little endian。

「endian」這個詞出自《格列佛遊記》。小人國的內戰就源於吃雞蛋時是究竟從大頭(Big-Endian)敲開還是從小頭(Little-Endian)敲開,由此曾發生過六次叛亂,其中一個皇帝送了命,另一個丟了王位。

我們一般將endian翻譯成「字元序」,將big endian和little endian稱作「大尾」和「小尾」。

1、字元編碼、內碼,順帶介紹中文字編碼

字元必須編碼後才能被電腦處理。電腦使用的缺省編碼方式就是電腦的內碼。早期的電腦使用7位的ASCII編碼,為了處理中文字,程式員設計了用於簡體中文的big5和用於繁體中文的big5。

big5(1980年)一共收錄了7445個字元,包括6763個中文字和682個其它符號。中文字區的內碼範圍高字元從B0-F7,低字元從A1-FE,佔用的碼位是72*94=6768。其中有5個空位是D7FA-D7FE。

big5支援的中文字太少。1995年的中文字擴展規範GBK1.0收錄了21886個符號,它分為中文字區和圖形符號區。中文字區包括21003個字元。2000年的GB18030是取代GBK1.0的正式國家標準。該標準收錄了27484個中文字,同時還收錄了藏文、蒙文、維吾爾文等主要的少數民族文字。現在的PC平台必須支援GB18030,對嵌入式產品暫不作要求。所以手機、MP3一般只支援big5。

從ASCII、big5、GBK到GB18030,這些編碼方法是向下兼容的,即同一個字元在這些方案中總是有相同的編碼,後面的標準支援更多的字元。在這些編碼中,英文和中文可以統一地處理。區分中文編碼的方法是高字元的最高位不為0。按照程式員的稱呼,big5、GBK到GB18030都屬於雙字元字元集 (DBCS)。

有的中文Windows的缺省內碼還是GBK,可以透過GB18030升級包升級到GB18030。不過GB18030相對GBK增加的字元,普通人是很難用到的,通常我們還是用GBK指代中文Windows內碼。

這裡還有一些細節:

  • big5的原文還是區位碼,從區位碼到內碼,需要在高字元和低字元上分別加上A0。

  • 在DBCS中,GB內碼的存儲格式始終是big endian,即高位在前。

  • big5的兩個字元的最高位都是1。但符合這個條件的碼位只有128*128=16384個。所以GBK和GB18030的低字元最高位都可能不是1。不過這不影響DBCS字元流的解析:在讀取DBCS字元流時,只要遇到高位為1的字元,就可以將下兩個字元作為一個雙字元編碼,而不用管低字元的高位是什麼。

2、Unicode、UCS和UTF

前面提到從ASCII、big5、GBK到GB18030的編碼方法是向下兼容的。而Unicode只與ASCII兼容(更準確地說,是與ISO-8859-1兼容),與GB碼不兼容。例如「漢」字的Unicode編碼是6C49,而GB碼是BABA。

Unicode也是一種字元編碼方法,不過它是由國際組織設計,可以容納全世界所有語言文字的編碼方案。Unicode的學名是"Universal Multiple-Octet Coded Character Set",簡稱為UCS。UCS可以看作是"Unicode Character Set"的縮寫。

根據維基百科全書(http://zh.wikipedia.org/wiki/)的記載:歷史上存在兩個試圖獨立設計Unicode的組織,即國際標準化組織(ISO)和一個軟體製造商的協會(unicode.org)。ISO開發了ISO 10646項目,Unicode協會開發了Unicode項目。

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/mman.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#define FILE_LENGTH 10000

int main(int argc,char *argv[])
{
        if(argc!=2)
    {
        printf("Usage: %s filename\n",argv[0]);
        return 0;
    }
        int fd,count=0;
        char *map_memory,*ca;
        
        fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        
        lseek(fd, FILE_LENGTH+1, SEEK_SET);
        write(fd, "", 1);
        lseek(fd, 0, SEEK_SET);
        map_memory =(char*) mmap(0, FILE_LENGTH, PROT_WRITE, MAP_SHARED, fd, 0);
        close(fd);
        
        ca = map_memory;
        while( FILE_LENGTH>count && fgets(ca,FILE_LENGTH-count,stdin)!=NULL )
        {
                int tmp = strlen(ca);
                count += tmp;
                ca += tmp;
        }
        
        munmap(map_memory, FILE_LENGTH);
        return 0;
}

 

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/mman.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#define FILE_LENGTH 10000

int main(int argc,char *argv[])
{
        if(argc!=4)
    {
        printf("Usage: %s filename start_pos end_pos\n",argv[0]);
        return 1;
    }
        int start_pos=0, end_pos=0;
        start_pos = atoi(argv[2]);
        end_pos = atoi(argv[3]);
        if(start_pos<0 || end_pos>FILE_LENGTH || start_pos>end_pos)
        {
                puts("start_pos or end_pos error. Please try again.");
        return 1;
        }
        int fd,i;
        char *map_memory;
        
        fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        
        lseek(fd, FILE_LENGTH+1, SEEK_SET);
        write(fd, "", 1);
        lseek(fd, 0, SEEK_SET);
        map_memory =(char*) mmap(0, FILE_LENGTH, PROT_WRITE, MAP_SHARED, fd, 0);
        close(fd);
        
        printf("Substring from [%d] to [%d] is: ",start_pos,end_pos);
        for(i=start_pos-1;i<end_pos;i++)
                printf("%c",*(map_memory+i));
        puts("");
        
        munmap(map_memory, FILE_LENGTH);
        return 0;
}

Posted by 和風信使 at 痞客邦 PIXNET 留言(1) 引用(0) 人氣()

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("lock.txt",O_RDWR|O_APPEND);
        //printf("fd = %d\n",fd);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))==0)
                        printf("F_WRLCK success.\n");
                else 
                {
                        printf("F_WRLCK fail.\n");
                        return 0;
                }
        }
        else
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))==0)
                        printf("F_RDLCK success.\n");
                else 
                {
                        printf("F_RDLCK fail.\n");
                        return 0;
                }
        }
        ia= 0;
        do
        {
                printf("If you want to unlock file and end program,\n");
                printf("please input 1 -> \n");
                scanf("%d",&ia);
        }while(ia!=1);
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("3.not use lock\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("lock.txt",O_RDWR|O_APPEND);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))!=0)
                        printf("F_WRLCK fail.\n");
                else 
                        printf("F_WRLCK success.\n");
        }
        else if(ia==2)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))!=0)
                        printf("F_RDLCK fail.\n");
                else 
                        printf("F_RDLCK success.\n");
        }
        char ca[10000];
        if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
        else
        {
                printf("Read file:\n");
                puts(ca);
        }
        strcpy(ca,"\n\nab write success.\n");
        if(write(fd, ca, strlen(ca))<0)printf("Can't write file.\n");
        else
        {
                printf("write file success.\n");
        }
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

/*
mount /dev/sda1 /mnt
mount -o remount,mand /mnt
*/
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("mandlock.txt",O_RDWR|O_APPEND);
        //printf("fd = %d\n",fd);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))==0)
                        printf("F_WRLCK success.\n");
                else 
                {
                        printf("F_WRLCK fail.\n");
                        return 0;
                }
        }
        else
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))==0)
                        printf("F_RDLCK success.\n");
                else 
                {
                        printf("F_RDLCK fail.\n");
                        return 0;
                }
        }
        ia= 0;
        do
        {
                printf("If you want to unlock file and end program,\n");
                printf("please input 1 -> \n");
                scanf("%d",&ia);
        }while(ia!=1);
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("3.not use lock\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("mandlock.txt",O_RDWR|O_APPEND);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))!=0)
                        printf("F_WRLCK fail.\n");
                else 
                        printf("F_WRLCK success.\n");
        }
        else if(ia==2)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))!=0)
                        printf("F_RDLCK fail.\n");
                else 
                        printf("F_RDLCK success.\n");
        }
        char ca[10000];
        if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
        else
        {
                printf("Read file:\n");
                puts(ca);
        }
        strcpy(ca,"\n\nab write success.\n");
        if(write(fd, ca, strlen(ca))<0)printf("Can't write file.\n");
        else
        {
                printf("write file success.\n");
        }
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<sstream>
using namespace std;

int freeFrameList[] = {4,7,8,5,1,2,11,12,10,13,14,15};
int freeFrameCnt = 12, freeFrameIndex = 0;
string frame[16] = {"ee","","","ww","","","gg","","","ff","","","","","",""};
string processA[] = {"ab","ef","cd","gh","xa","ta","ab","cg"};
string processB[] = {"rx","yy","zz","ww","mr","mk","fn","zx"};

void show_all(bool ba=false)
{
        if(!ba)
        {
                for(int i=0;i<79;i++)
                        cout<<"=";
                cout<<endl;
        }
        printf("\n%s\n","ProcessA");
        for(int i=0;i<8;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<8;i++)printf("%3s",processA[i].c_str());
        printf("\n\n%s\n","ProcessB");
        for(int i=0;i<8;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<8;i++)printf("%3s",processB[i].c_str());
        printf("\n\n%s\n","freeFrameList");
        for(int i=freeFrameIndex;i<freeFrameCnt;i++)printf("%3d",freeFrameList[i]);
        printf("\n\n%s\n","frame");
        for(int i=0;i<16;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<16;i++)printf("%3s",frame[i].c_str());
        puts("");puts("");
}

int main()
{
        string sa;
        show_all(true);
        for(int i=0;i<freeFrameCnt && cout<<"Enter next (ProcessName/page No) -> " && getline(cin,sa);i++)
        {
                sa.erase(0,sa.size()-3);
                istringstream ssin(sa);
                char ca;
                int ia;
                ssin>>ca>>ia;
                switch(ca)
                {
                case 'a':case 'A':
                        frame[freeFrameList[freeFrameIndex++]] = processA[ia];
                        break;
                case 'b':case 'B':
                        frame[freeFrameList[freeFrameIndex++]] = processB[ia];
                        break;
                }
                show_all();
        }
}
/*
ProcessA 0
ProcessB 1
ProcessA 4
ProcessB 5
ProcessB 7
ProcessA 7
ProcessA 2
ProcessB 6
*/

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()

/*
    gcc -o a a.c -pthread
    ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a
*/
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
void inc(void){
        int i=0;
        for(i=0;i<25000000;i++){
                count++;
        }
        pthread_exit(NULL);
}
void dec(void){
        int i=0;
        for(i=0;i<25000000;i++){
                count--;
        }
        pthread_exit(NULL);
}
int main(void){
        int i=0;
        pthread_t id[4];        
        pthread_create(&id[0],NULL,(void*)dec,NULL);
    pthread_create(&id[1],NULL,(void*)inc,NULL);
    pthread_create(&id[2],NULL,(void*)dec,NULL);
    pthread_create(&id[3],NULL,(void*)inc,NULL);
    for(i=0;i<4;i++)
    {
                pthread_join(id[i],NULL);       
        }
        printf("\noutput is %d\n",count);
}

 

/*
    gcc -o a a.c -pthread
    ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a
*/
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
sem_t sem;

void inc(void){
        int i=0;
        for(i=0;i<25000000;i++){
        sem_wait(&sem);
                count++;
        sem_post(&sem);
        }
        pthread_exit(NULL);
}
void dec(void){
        int i=0;
        for(i=0;i<25000000;i++){
        sem_wait(&sem);
                count--;
        sem_post(&sem);
        }
        pthread_exit(NULL);
}
int main(void){
    sem_init(&sem,0,1);
        int i=0;
        pthread_t id[4];        
        pthread_create(&id[0],NULL,(void*)dec,NULL);
    pthread_create(&id[1],NULL,(void*)inc,NULL);
    pthread_create(&id[2],NULL,(void*)dec,NULL);
    pthread_create(&id[3],NULL,(void*)inc,NULL);
    for(i=0;i<4;i++)
    {
                pthread_join(id[i],NULL);       
        }
        printf("\noutput is %d\n",count);
    sem_destroy(&sem);
    return 0;
}

 

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include </usr/include/semaphore.h>

#define BUFF_SIZE   5           /* total number of slots */
#define NP          3           /* total number of producers */
#define NC          3           /* total number of consumers */
#define NITERS      4           /* number of items produced/consumed */

typedef struct {
    int buf[BUFF_SIZE];   /* shared var */
    int in;               /* buf[in%BUFF_SIZE] is the first empty slot */
    int out;              /* buf[out%BUFF_SIZE] is the first full slot */
    sem_t full;           /* keep track of the number of full spots */
    sem_t empty;          /* keep track of the number of empty spots */
    sem_t mutex;          /* enforce mutual exclusion to shared data */
} sbuf_t;

sbuf_t shared;

void *Producer(void *arg)
{
    int i, item, index;

    index = (int)arg;

    for (i=0; i < NITERS; i++) {

        /* Produce item */
        item = i;       

        /* Prepare to write item to buf */

        /* If there are no empty slots, wait */
        sem_wait(&shared.empty);
        /* If another thread uses the buffer, wait */
        sem_wait(&shared.mutex);
        shared.buf[shared.in] = item;
        shared.in = (shared.in+1)%BUFF_SIZE;
        printf("[P%d] Producing %d ...\n", index, item); fflush(stdout);
        /* Release the buffer */
        sem_post(&shared.mutex);
        /* Increment the number of full slots */
        sem_post(&shared.full);

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    }
    return NULL;
}

void *Consumer(void *arg)
{
    /* Fill in the code here */
    int i, item, index;

    index = (int)arg;

    for (i=0; i < NITERS; i++) {
        /* Prepare to read item from buf */

        /* If there are no full spots, wait */
        sem_wait(&shared.full);
        /* If another thread uses the buffer, wait */
        sem_wait(&shared.mutex);
        
        /* Consume item */
        item = shared.buf[shared.out];
        shared.out = (shared.out+1)%BUFF_SIZE;
        printf(" ------> [P%d] Consuming %d ...\n", index, item); fflush(stdout);
        /* Release the buffer */
        sem_post(&shared.mutex);
        /* Increment the number of full slots */
        sem_post(&shared.empty);

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t idP, idC;
    int index;

    sem_init(&shared.full, 0, 0);
    sem_init(&shared.empty, 0, BUFF_SIZE);

    /* Insert code here to initialize mutex*/
    sem_init(&shared.mutex, 0, 1);

    for (index = 0; index < NP; index++)
    {  
       /* Create a new producer */
       pthread_create(&idP, NULL, Producer, (void*)index);
    }

    /* Insert code here to create NC consumers */
    for (index = 0; index < NC; index++)
    {  
       /* Create a new producer */
       pthread_create(&idC, NULL, Consumer, (void*)index);
    }

    pthread_exit(NULL);
}

Posted by 和風信使 at 痞客邦 PIXNET 留言(0) 引用(0) 人氣()