'Thinking about'에 해당되는 글 32건

  1. 2010.05.06 Python HW 1번문제
  2. 2010.04.27 그래픽스 실습 4.27
  3. 2010.04.15 파이썬 c API 하다 만거
  4. 2010.03.25 네트워크 홈워크 1
  5. 2010.03.18 GeneralTree to BinaryTree 2
  6. 2010.03.18 봄날은 간다 자우림
  7. 2010.03.18 어떻게 하는거더라..??ㅋㅋ
  8. 2010.03.17 오늘 하루 종일 날린 거!!! 까먹지 말자.ㅠㅠㅠㅠㅠ
  9. 2010.03.16 Pthread with Semaphore <posix>
  10. 2010.03.15 Posix Thread 예제 소스

Python HW 1번문제

import os.path

import glob
import cStringIO
import os
import sys
if(len(sys.argv)!=2):
    print("Usage : python <Script name> <Dir Name>")
    sys.exit(1)

files={}
id=0

def countWord(filename):
    in_file = open(filename)
    text = in_file.read()
    in_file.close()
    strIO = cStringIO.StringIO(text)
    filelines = strIO.readlines()
    numOfWd=0
    numOfLn=0
    word=[]
    
    for line in filelines:
        word+=line.split()
        numOfLn+=1
    for w in word:
        numOfWd+=1  
        
    return numOfWd, numOfLn
    

def searchDir(dirName):
    fileList = glob.glob(dirName)
    for fullFile in fileList:
        if os.path.isdir(fullFile):
            searchDir(fullFile+"/*")
        else:
            d_name = os.path.dirname(fullFile)
            f_name = os.path.basename(fullFile)
            words,lines = countWord(fullFile)
            value=(d_name,f_name,lines,words)
            global id
            id+=1
            files[id]=value
  


searchDir(sys.argv[1]+"/*")
f_keys = files.keys()
for a in f_keys:
    print "id", a
    info = files[a]
    print "Path : ", info[0]
    print "File name : ", info[1]
    print "Number of lines :", info[2]
    print "Number of Words :",info[3]
    

 

'Sorce Bank' 카테고리의 다른 글

Python BST + AVL  (0) 2010.05.08
Python HW 2번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25

그래픽스 실습 4.27



#include
#include 


void draw_axes();
void init();
void draw_drag();
void display(void);
void mouse(int button,int status,int x, int y);
void motion(int,int);

int last_x,last_y;			//last (x,y) position , where the left button pressed.
int current_x, current_y;   // current (x,y) position 
bool b_draw_dragbox = false;

int main()
{
	glutCreateWindow("TransFormation");
	glutDisplayFunc(display);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);
	init();
	
	glutMainLoop();

	return 0;
}

void init()
{

	glClearColor(1.0f,1.0f,1.0f,1.0f);

}

void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	// set the current camera
	// f) extrinsic camera property, which can be specified by GL_MODELVIEW matirix
	// s) intrinsic camera property, which can be specified by GL_PROJECTION matrix

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1,1,- 1,1 ,-1, 1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();														// M = I
	gluLookAt(0, 0, 1, 0, 0, 0, 0, 1 , 0);
	
	draw_axes();
	// Object를 조작함.
	//glRotatef(75.0f,0,0,1);											// R 메트릭스    M *=R   => M=R 
	//glScalef(2.0f,2.0f,2.0f);										// S 메트릭스		M *=S   => M=RS
	glTranslatef(0.3f,0.3f,0.0f);										// T 메트릭스		M *=T   => M=RST
																				// T ( S ( Rx))
	// Model Matrix Continue....																		M'  = RSTx    => T먼저 적용됨.

	// Draw DragBox
	if(b_draw_dragbox)
		draw_drag();

	

	//Drawing an object (a red box)
	// Object는 절대 건들이지 않는다. 메트릭스만 곱해서 조절 ->그리는건 조형대 애들이. 
	glColor3f(1.0f,0.0f,0.0f);
	glBegin(GL_QUADS);
	// -------------------------------
	glVertex2f(0.5f,0.5f);
	glVertex2f(-0.5f,0.5f);											// x메트릭스
	glVertex2f(-0.5f,-0.5f);
	glVertex2f(0.5f,-0.5f);
	// -------------------------------
	glEnd();
																				//  = > Tx
	glFlush();


}

void draw_drag()
{
	glColor3f(0.0f,1.0f,0.0f);
	glBegin(GL_LINE_LOOP);
	glVertex2f(last_x,last_y);
	glVertex2f(last_x,current_y);
	glVertex2f(current_x,current_y);
	glVertex2f(current_x,last_y);
	glEnd();
	printf("adfasd");

}
void draw_axes()
{
	glMatrixMode(GL_MODELVIEW);
	glBegin(GL_LINES);

	glColor3f(1.0f,0.0f,0.0f);
	glVertex2d(-5,0);
	glVertex2d(5,0);


	glColor3f(1.0f,1.0f,0.0f);
	glVertex2d(0,-5);
	glVertex2d(0,5);
	glEnd();
	glFlush();

}

void mouse(int button,int state,int x, int y)
{
	if( button == GLUT_LEFT_BUTTON&& state == GLUT_DOWN)
	{
		printf("left mouse button is pressed!\n");
		last_x = x;
		last_y = y;
		b_draw_dragbox=true;
		// 네모 그리고 
	} else if( button == GLUT_LEFT_BUTTON && state == GLUT_UP)
	{
		printf("left mouse button is Releassed!\n");
		b_draw_dragbox=false;
		// 네모지우고
	}
}


void motion(int x,int y)
{
	current_x =x;
	current_y = y;
	printf("mouse is dragging : x : %d   y: %d \n",x,y);

}

'Sorce Bank' 카테고리의 다른 글

Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06
파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25
GeneralTree to BinaryTree  (2) 2010.03.18

파이썬 c API 하다 만거

#include "Python.h"
//http://blog.redjini.com/94
//http://docs.python.org/c-api/list.html
//http://www.python.or.kr/pykug/C_20_c8_ae_c0_e5_b8_f0_b5_e2_20_b8_b8_b5_e9_b1_e2

static PyObject *ErrorObject;

 static PyObject* sample_dictest(PyObject *self, PyObject *args)
{
    PyObject* dic;
    int len;

    if (!PyArg_ParseTuple(args, "O", &dic)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyDict_Check(dic)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyDict_Size(dic);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is dictionary of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}


static PyObject* sample_system(PyObject *self, PyObject *args)
{
    char *command;
    int sts;
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}

 static PyObject* my_sort(PyObject *self, PyObject *args)
{
    PyObject* list;
    int len;

    if (!PyArg_ParseTuple(args, "O", &list)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyList_Check(list)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyList_Size(list);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is List of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}



static struct PyMethodDef my_methods[] = {
 {"system",       sample_system,    METH_VARARGS}, /* name, address */
 {"dictest",      sample_dictest,   METH_VARARGS},
 {"sort",         my_sort,          METH_VARARGS},
 {NULL,         NULL}                              /* end, for initmodule */
};

void initsample()
{
    PyObject *m;
    /* 모듈을 생성하고 함수를 등록한다 */
    m = Py_InitModule("mylib", my_methods);        /* registration hook */
    /* 기타의 초기화 처리 */
    ErrorObject = Py_BuildValue("s", "sample error");
    /* ... */
}

'Sorce Bank' 카테고리의 다른 글

Python HW 1번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
네트워크 홈워크 1  (0) 2010.03.25
GeneralTree to BinaryTree  (2) 2010.03.18
Java Binary Tree  (0) 2010.03.14

네트워크 홈워크 1


/*
Student ID : 20052532
Name : Jea Young Park
*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void display();
void exceptionHandler(char * msg);

int peertcpSocket = -1;	// peer socket

int main(int argc, char **argv)
{

  int tcpServ_sock;

  struct sockaddr_in tcpServer_addr;
  struct sockaddr_in tcpClient_addr;
  struct sockaddr_in newTcp_addr;

  int clnt_len;

  fd_set reads, temps;
  int fd_max;

  char command[1024];
  char comd[1024];


  char *tcpport = NULL;
  char *userid = NULL;
  int command_len;
  struct hostent *hostp;
  char* addr;
  char* port;
// NEED TO ADD SOME VARIABLES

  if(argc != 3){
    printf("Usage : %s  \n", argv[0]);
    exit(1);
  }


  display();
  tcpport = argv[1];
  userid = argv[2];


	// NEED TO CREATE A SOCKET FOR TCP SERVER
  peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
  tcpServ_sock = socket(PF_INET, SOCK_STREAM, 0);
  if (tcpServ_sock == -1||peertcpSocket==-1)
  {
      exceptionHandler("socket() error");
      exit(1);
  }

  memset(&tcpServer_addr,0,sizeof tcpServer_addr);
  tcpServer_addr.sin_family = AF_INET;
  tcpServer_addr.sin_addr.s_addr = INADDR_ANY;
  tcpServer_addr.sin_port = htons((u_short)atoi(tcpport));

	// NEED TO bind
  if(bind(tcpServ_sock,(struct sockaddr*)&tcpServer_addr,sizeof tcpServer_addr)==-1)
  {
      exceptionHandler("bind() error");
      exit(1);
  }


	// NEED TO listen
  if(listen(tcpServ_sock,SOMAXCONN)==-1)
  {
      exceptionHandler("listen() error");
      exit(1);
  }
	// initialize the select mask variables and set the
	// mask with stdin and the tcp server socket
  FD_ZERO(&reads);
  FD_SET(tcpServ_sock,&reads);
  FD_SET(peertcpSocket,&reads);
  FD_SET(fileno(stdin),&reads);

  printf("%s> \n", userid);

  while(1)
  {
    int nfound;
    temps = reads;

    nfound = select(fd_max+1, &temps, 0, 0, NULL);

	if(FD_ISSET(fileno(stdin), &temps)) {
		// Input from the keyboard
		fgets(command, sizeof (command), stdin);
  		FD_CLR(fileno(stdin), &temps);
                strcpy(comd,command);
                char* cmd = strtok(command," \n");
           


	// NEED TO IMPLEMENT for input from keybord
                if(strcmp(cmd,"@conn")==0){
                    addr = strtok (NULL, " \n");
                    port = strtok (NULL, " \n");

                    hostp = gethostbyname(addr);
                    
                    memset((void *) &newTcp_addr, 0, sizeof (newTcp_addr));
                    newTcp_addr.sin_family = AF_INET;
                    memcpy((void *) &newTcp_addr.sin_addr, hostp->h_addr, hostp->h_length);
                    newTcp_addr.sin_port = htons((u_short)atoi(port));
                    
                    if(connect(peertcpSocket,(struct sockaddr*)&newTcp_addr,sizeof newTcp_addr)==-1){
                        exceptionHandler("connect() error");
                        exit(1);
                    }

                } else if(strcmp(cmd,"@quit")==0)
                {
                    close(peertcpSocket);
                    fprintf(stdout,"Closed socket descriptor : %d\n",peertcpSocket);
                    peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
                }else if(strcmp(cmd,"@exit")==0)
                {
                    close(peertcpSocket);
                    close(tcpServ_sock);
                    exit(0);
                } else {
                    strcpy(command,comd);
                    strcpy(comd,userid);
                    strcat(comd , " ) ");
                    strcat(comd,command);
                    write(peertcpSocket,comd,strlen(comd));
                }

  		printf("%s> \n", userid);
	}
	else if(FD_ISSET(tcpServ_sock, &temps))
	{
		//connect request from a peer
           clnt_len = sizeof tcpClient_addr;
           close(peertcpSocket);
           peertcpSocket =accept(tcpServ_sock,(struct sockaddr*)&tcpClient_addr,&clnt_len);
           if(peertcpSocket == -1)
           {
                     exceptionHandler("accept() error");
                     exit(1);
           }
           fprintf(stdout,"New Talk : host %s, port %d, socket %d\n",inet_ntoa(tcpClient_addr.sin_addr),ntohs(tcpClient_addr.sin_port),peertcpSocket);

	}
	else if(FD_ISSET(peertcpSocket, &temps))
	{

            command_len=read(peertcpSocket,command,sizeof command);
            if(command_len == -1)
            {
                   exceptionHandler("read() error");
                   exit(1);
            }else if(command_len == 0)
            {
                close(peertcpSocket);
                peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
                fprintf(stdout,"Closed socket descriptor : %d\n",peertcpSocket);
            }else {
            command[command_len] = '\0';
            fputs(command,stdout);
            fputs("\n",stdout);
            }
	}

  }//while End
}//main End

void display()
{
	printf("Student ID : 20052532 \n");
	printf("Name : JeaYoung  \n");
}
void exceptionHandler(char * msg)
{
    fputs(msg,stderr);
    fputs("\n",stderr);
}




'Sorce Bank' 카테고리의 다른 글

그래픽스 실습 4.27  (0) 2010.04.27
파이썬 c API 하다 만거  (0) 2010.04.15
GeneralTree to BinaryTree  (2) 2010.03.18
Java Binary Tree  (0) 2010.03.14
Python Client  (0) 2010.03.14

GeneralTree to BinaryTree


main.cpp
/*
  Input File Command Manual

  1. insert  
	This Command Call insert Function.
	If  is Root,  will insert to Root Node.

  2. Gen2Bin
	This Command make General Tree Binary Tree.

  3. clearBinary
	This Command Clear data(link data : R_child, L_child) of Binary Tree.
	You Must call This command, When You insert Node after calling Gen2Bin command.

  4. inorder
	This Command is In-order Traversal.

  5. preorder
	This Command is Pre-order Traversal.

  6. postorder
	This Command is Post-order Traversal.

  7. end
	End of input File.

  #- all Commands are case-sensitive  -#
*/


//---------------------------------------------------------------------------

#pragma hdrstop
#include "GeneralTree.h"
#include 
#include 
#include 
//---------------------------------------------------------------------------

using namespace std;
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
	string command;
	cout << "Enter Input File name : ";
	cin >> command;
	fstream i_file(command.c_str(), ios_base::in);
	cout << "Enter Output File name : ";
	cin >> command;
	fstream o_file(command.c_str(), ios_base::out);

	GeneralTree* tree = new GeneralTree(o_file);

	while(!i_file.eof()){
	i_file >> command ;
	if (strcmp(command.c_str(),"insert")==0) {
		string p;
		char a;
		i_file >>p >> a;
		if(strcmp(p.c_str(),"Root")==0)
		{
			tree->Insert(NULL,a);
		} else {
			tree->Insert(p[0],a);
		}
	} else if (strcmp(command.c_str(),"Gen2Bin")==0) {
			tree->General2Binary(tree->getRoot());
		   }
	else if (strcmp(command.c_str(),"clearBinary")==0) {
			tree->ClearBinary(tree->getRoot());
		 }

	 else if (strcmp(command.c_str(),"inorder")==0) {
			 tree->inOrder(tree->getRoot());
			 o_file << "\n";

	 }
	  else if (strcmp(command.c_str(),"preorder")==0) {
			tree->preOrder(tree->getRoot());
			 o_file << "\n";
	 }
	  else if (strcmp(command.c_str(),"postorder")==0) {
			tree->postOrder(tree->getRoot());
			o_file << "\n";
	 }
	 else if (strcmp(command.c_str(),"end")==0) {
				cout <<"[Finished]\n";
				tree->~GeneralTree();
				i_file.close();
				o_file.close();
				return 0;
	 }
	 else {
				cout <<"Unknown Command Error!! : "<< command<<"\n";
				tree->~GeneralTree();
				i_file.close();
				o_file.close();
				return 1;
			}
	}
 }
//---------------------------------------------------------------------------
Node.h
#include 

#ifndef NODE_H
#define NODE_H
template 
class Node
{
public:

	Node(Ty d)
	{
		data=d;
		//children.reserve(10);
	}
	inline void setRight(Node* node){ R_child = node;}
	inline void setLeft(Node* node) { L_child = node;}

	inline Node* getRight(){return R_child;}
	inline Node* getLeft() {return L_child;}

	inline Ty getData()const { return data; }
	std::vector* > children;
private:
	Node *R_child;
	Node *L_child;
	Ty data;
};

#endif
GeneralTree.h
#ifndef GENERALTREE_H
#define GENERALTREE_h
#include 
#include 

#include 

#include "Node.h"
using namespace std;


template 
class GeneralTree
{
public:
	GeneralTree(ostream o_stream)
	{
		root = new Node(NULL);
		NullNode = new Node(NULL);
		os = o_stream;
	}

	~GeneralTree()
	{
		delete root;
		delete NullNode;
	}

	Node* findNode(Node* node,Ty data);
	bool Insert(Ty Dop,Ty data);
	Node* makeNode(Ty data);
	void General2Binary(Node* CurrentNode);
	void inOrder(Node *node);
	void preOrder(Node *node);
	void postOrder(Node *node);
	void showData(Node *node);
	void ClearBinary( Node *node);

	inline Node* getRoot() const {return root; }



private:
	Node* root;
	Node* NullNode;
	ostream os;

};

template 
void GeneralTree::General2Binary(Node* CurrentNode)
{
	typedef vector< Node* >::iterator Child_t;
	if(!(CurrentNode->children.empty()))
	{
		for(Child_t it= CurrentNode->children.begin();it != CurrentNode->children.end()-1 ; it++)
		{
			if(it == CurrentNode->children.begin())
			{
				CurrentNode->setLeft(*it);
				(*it)->setRight(*(it+1));
				General2Binary(*it);
			} else {
				(*it)->setRight(*(it+1));
				General2Binary(*it);
			}
		}
	}
}

/*
 * Dop : Data of Parent
 *       if Dop is NULL , data Will be Inserted to Root.
 *       if Dop could not find, data Will Not be inserted.
 *       if Dop was Found , data will be Inserted to Child of Dop.
 * data : A data to insert
 */
template 
bool GeneralTree::Insert(Ty Dop, Ty data)
{
	if(root->getData() == NULL)
	{
		root = makeNode(data);
		return true;
	} else {
		Node* parent;
		parent = findNode(root,Dop);
		if(parent == NullNode)
		{
			std::cerr << " 원하는 부모의 값이 없습니다. \n";
			return false;
		} else {
			parent->children.push_back(makeNode(data));
			return true;
		}
	}

}

template 
Node* GeneralTree::findNode(Node* node,Ty data)
{
	typedef vector< Node* >::iterator Child_t;
	Node* temp;
	if(node->getData() == data)
		return node;
	else {
		Node* Parent=node;
		Child_t begin = Parent->children.begin();
		for(Child_t it = begin; it != Parent->children.end(); it++)
		{
			temp = findNode((*it),data);
			if(temp != NullNode )
				return temp;
		}
		return NullNode;
	}

}
template 
Node* GeneralTree::makeNode(Ty data)
{
	Node* new_node = new Node(data);
	new_node->setLeft(NullNode);
	new_node->setRight(NullNode);
	return new_node;
}

template 
void GeneralTree::showData(Node *node)
{
	os << node->getData() <<" ";
}


template 
void GeneralTree::preOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "PreOrder : ";

	showData(node);
	preOrder(node->getLeft());
	preOrder(node->getRight());
}

template 
void GeneralTree::inOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "InOrder : ";

	inOrder(node->getLeft());
	showData(node);
	inOrder(node->getRight());
}

template 
void GeneralTree::postOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "PostOrder : ";

	postOrder(node->getLeft());
	postOrder(node->getRight());
	showData(node);
}

template 
void GeneralTree::ClearBinary(Node *node)
{
	if(node == NullNode ) return ;
	ClearBinary(node->getLeft());
	ClearBinary(node->getRight());
	node->setLeft(NullNode);
	node->setRight(NullNode);
}

#endif

'Sorce Bank' 카테고리의 다른 글

파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25
Java Binary Tree  (0) 2010.03.14
Python Client  (0) 2010.03.14
Python Server  (0) 2010.03.14

봄날은 간다 자우림

'Daily Story' 카테고리의 다른 글

어떻게 하는거더라..??ㅋㅋ  (0) 2010.03.18

어떻게 하는거더라..??ㅋㅋ


요조 - 연애는 어떻게 하는 거였더라

연애는 어떻게 하는 거 였더라

새까맣게 다 잊어 버렸네

한땐 잘 나갔던것 같은데

어쩌다가 이렇게 되버렸나..

 

어쩜 넌 늙지도 않는 거냐고

스물여섯 처럼 안 보인다고

사람들 내게 말해 주지만

내 맘속 외로움도 보일까나..


'Daily Story' 카테고리의 다른 글

봄날은 간다 자우림  (0) 2010.03.18

오늘 하루 종일 날린 거!!! 까먹지 말자.ㅠㅠㅠㅠㅠ

왜!!!

템플릿은 클레스는 구현과 선언을 
헤더와 CPP파일로 나누어서 하면

링킹에러가 난다..

왜일까??


이거때메 오늘 하루종일 뻘짓.....ㅜㅜ..ㅜ.ㅡ

반드시

템플릿 클레스는 선언과 구현을 하나의 파일 내에서 할것!!!

Pthread with Semaphore <posix>

아래 Mutex로 동기화 했던걸 Semaphore로 변형 시킨거 위에껀 이름있는 세마포어??? 어래껀 익명 세미포어
#include 
#include 
#include 
#include 
#include  //for   O_CREAT
#include 

using namespace std;
sem_t *mysem;

struct arg
{
    int start;
    int end;
    int time;
    string name;
};


void *cnt(void* a)
{
    struct arg* temp=(struct arg*)a;

    for(int i= temp->start; i < temp->end;i++)
    {
        sem_wait(mysem);
        cout << temp->name <<" : " << i << endl;
        sem_post(mysem);
        sleep(temp->time);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t td1,td2,td3;
    struct arg ar1,ar2,ar3;
    void* state;
    ar1.start=0;
    ar1.end=20;
    ar1.name=string("thread1");
    ar1.time=1;

    ar2.start=-10;
    ar2.end=0;
    ar2.name=string("thread2");
    ar2.time=2;

    ar3.start=100;
    ar3.end=110;
    ar3.name=string("thread3");
    ar3.time=3;
    sem_unlink("mysem"); //세마포어 삭제
    if((mysem = sem_open("mysem", O_CREAT, 0777, 1)) == NULL)
// /dev/shm에 해당이름의 세마포어 파일로 생성됨.
// O_CREAT : 파일이 존재하면 따로 생성하지 않음 , 0777 퍼미션
    {
        perror("Sem Open Error");
        return 1;
    }
    pthread_create(&td1,NULL,cnt,(void*)&ar1);
    pthread_create(&td2,NULL,cnt,(void*)&ar2);
    pthread_create(&td3,NULL,cnt,(void*)&ar3);

    pthread_join(td1,&state);
    pthread_join(td2,&state);
    pthread_join(td3,&state);

    return 0;
}
#include 
#include 
#include 
#include 
#include 

using namespace std;
sem_t mysem;

struct arg
{
    int start;
    int end;
    int time;
    string name;
};


void *cnt(void* a)
{
    struct arg* temp=(struct arg*)a;

    for(int i= temp->start; i < temp->end;i++)
    {
        sem_wait(&mysem);
        cout << temp->name <<" : " << i << endl;
        sem_post(&mysem);
        sleep(temp->time);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t td1,td2,td3;
    struct arg ar1,ar2,ar3;
    void* state;
    ar1.start=0;
    ar1.end=20;
    ar1.name=string("thread1");
    ar1.time=1;

    ar2.start=-10;
    ar2.end=0;
    ar2.name=string("thread2");
    ar2.time=2;

    ar3.start=100;
    ar3.end=110;
    ar3.name=string("thread3");
    ar3.time=3;
    
    if(sem_init(&mysem,0,1) ==-1)
    {
        cerr <<"Error";
        exit(0);
    }


    pthread_create(&td1,NULL,cnt,(void*)&ar1);
    pthread_create(&td2,NULL,cnt,(void*)&ar2);
    pthread_create(&td3,NULL,cnt,(void*)&ar3);

    pthread_join(td1,&state);
    pthread_join(td2,&state);
    pthread_join(td3,&state);

    return 0;
}

'Computer 기타' 카테고리의 다른 글

C# UnitTest by csUnit  (0) 2010.07.02
Posix Thread 예제 소스  (0) 2010.03.15
자바 Tar 묶음 파일 만들기  (0) 2010.02.27
자바 - 정규표현식 예제입니다.<혼자보기용>  (0) 2010.02.27

Posix Thread 예제 소스

PThread 간단하게 쓰레드 생성하고 간단한 뮤텍스까지 들어있는 소스 입니다.
#include 
#include 
#include 
#include 
#include 

using namespace std;
pthread_mutex_t mutex;

struct arg
{
    int start;
    int end;
    int time;
    string name;
};


void *cnt(void* a)
{
    struct arg* temp=(struct arg*)a;

    for(int i= temp->start; i < temp->end;i++)
    {
        pthread_mutex_lock(&mutex);
        cout << temp->name <<" : " << i << endl;
        pthread_mutex_unlock(&mutex);
        sleep(temp->time);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t td1,td2,td3;
    struct arg ar1,ar2,ar3;
    void* state;
    ar1.start=0;
    ar1.end=20;
    ar1.name=string("thread1");
    ar1.time=1;

    ar2.start=-10;
    ar2.end=0;
    ar2.name=string("thread2");
    ar2.time=2;

    ar3.start=100;
    ar3.end=110;
    ar3.name=string("thread3");
    ar3.time=3;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&td1,NULL,cnt,(void*)&ar1);
    pthread_create(&td2,NULL,cnt,(void*)&ar2);
    pthread_create(&td3,NULL,cnt,(void*)&ar3);

    pthread_join(td1,&state);
    pthread_join(td2,&state);
    pthread_join(td3,&state);

    pthread_mutex_destroy(&mutex);

    return 0;
}

'Computer 기타' 카테고리의 다른 글

C# UnitTest by csUnit  (0) 2010.07.02
Pthread with Semaphore <posix>  (0) 2010.03.16
자바 Tar 묶음 파일 만들기  (0) 2010.02.27
자바 - 정규표현식 예제입니다.<혼자보기용>  (0) 2010.02.27
prev 1 2 3 4 next