2014. 6. 13. 15:39

[Linux Programming] 스레드만 종료 / pthread_cleanup_push, pthread_cleanup_pop으로 마무리 처리부 등록하기


* 프로세스에서 스레드만 종료시키고자 하는 경우

  1. 스레드 함수에서 return

  2. 스레드에서 pthread_exit 호출

  3.  다른 스레드에서 pthread_cancel 호출



* pthread_cancel

한 스레드가 같은 프로세스에 속한 다른 스레드의 취소를 요청할 수 있다.


#include <pthread.h>

int pthread_cancel(pthread_t tid);   

>> 인자

첫번째 : 스레드 ID

반환값 : 성공시 0, 실패시 오류번호





* 스레드 종료시 특정 함수들이 호출되도록 설정

  - 스레드 마무리 처리부, 

    스레드 마무리 처리부들은 한 스택에 등록되는데, 

    이는 마무리 처리부들이 등록된 순서의 역순을 호출된다는 의미(선입후출)


#include <pthrad.h>

void pthread_cleanup_push(void(*rtn)(void *), void *arg);

첫번째 인수 : rtn으로 지정된 마무리 함수를 스택에 등록

두번째 인수 : 마무리 처리부 함수의 인수


void pthread_cleanup_pop(int execute);

첫번째 인수 : 0이 아닌 값을 호출하면 마무리처리부에서 pop을 수행한다.



마무리 처리부가 호출되는 상황

* 스레드가 pthread_exit를 호출했다.

* 스레드가 취소 요청에 반응했다. (다른 스레드에서 pthread_cancel을 호출한 경우)

* 스레드가 execute인수에 0이 아닌 값을 넣어서 pthread_cleanup_pop 함수를 호출했다.



* 이 두 함수에 제약

** 이들은 매크로로 구현 될 수 있기 때문에 둘의 호출은 반드시 한 스레드의 같은 범위 안에서 짝을 이루어야 한다.) 

** pthread_cleanup_push, pthread_cleanup_pop은 셋트로 써야 한다.

**** 안그러면 컴파일 시 에러가 난다.

**** 짝을 맞춰주기 위해 pop(0) 방식으로 쓰기도 함

void *thr_fn1(void *arg)

{

pthread_cleanup_push( cleanup, NULL);

pthread_cleanup_pop(0);

       pthread_exit((void*)2);

}




예제 프로그램

#include "apue.h"

#include <pthread.h>


void cleanup(void *arg)

{

    printf("cleanup : %s\n", (char *)arg);

}


void * thr_fn1(void *arg)

{

    printf("thread 1 start\n");

    pthread_cleanup_push(cleanup, "thread 1 first handler");

    pthread_cleanup_push(cleanup, "thread 1 second handler");

    printf("thread 1 push complete\n");

    if (arg)

    {

        return ((void *)1);

    }

    pthread_cleanup_pop(0);

    pthread_cleanup_pop(0);

    return ((void *)1);

}


void * thr_fn2(void *arg)

{

    printf("thread 2 start \n");

    pthread_cleanup_push(cleanup, "thread 2 first handler");

    pthread_cleanup_push(cleanup, "thread 2 second handler");

    printf("thread 2 push complete\n");

    if (arg)

    {

        pthread_exit((void *)2);

    }

    pthread_cleanup_pop(0);

    pthread_cleanup_pop(0);

    pthread_exit((void *)2);

}


int main(void)

{

    int err;

    pthread_t tid1, tid2;

    void *tret;


    err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);


    if (err != 0 )

        err_quit("can't create thread 1: %s\n", strerror(err));


    err = pthread_create(&tid2, NULL, thr_fn2, (void *)1);


    if (err != 0 )

        err_quit("cna't create thread 2: %s\n", strerror(err));


    err = pthread_join(tid1, &tret);

    if (err != 0)

        err_quit("can't join with thread 1: %s \n", strerror(err));

    printf("thread 1 exit code %d \n", (int)tret);

    err = pthread_join(tid2, &tret);


    if(err != 0)

        err_quit("can't join with thread 2: %s \n", strerror(err));

    printf("thread 2 exit code %d\n", (int)tret);

    exit(0);


}


$ ./11-5

thread 2 start

thread 1 start

thread 1 push complete

thread 2 push complete

thread 1 exit code 1

cleanup : thread 2 second handler

cleanup : thread 2 first handler

thread 2 exit code 2


return으로 종료된 경우는 스레드 마무리 처리부를 처리하지 않았다.

pthread_exit 로 종료한 경우에 스레드 마무리 처리부를 호출하였다.


출처 : 유닉스고급프로그램 11-5


Posted by Triany
2014. 6. 13. 11:36

* pthread_create

 헤더

 #include  <pthread.h>

 원형

 int pthread_create(pthread_t * thread, const pthread_attr_t *attr,

     void* (*start_routine)(void*), void *arg);

 인자

 첫번째 : 생성된 스레드의 ID를 저장할 변수의 포인터 옴

 두번째 : 스레드 특징을 설정할때 사용됨, 주로 NULL이 옴

 세번째 : 스레드가 생성되고 나서 실행될 함수가 옴

 네번째 : 세번째 인자에서 호출될 함수에 전달하고자 하는 인자의 값


* pthread_join

 헤더

 #include <pthread.h>

 

 int pthread_join(pthread_t th, void **thread_return);

 인자설명

 첫번째 : 스레드 ID가 옴. 이 ID가 종료할 때까지 실행을 지연

 두번째 : 스레드 종료시 반환값 받음



정확하지 않은 tip!!

pthread_join의 반환값이 스레드 종료시 반환값인데,

스레드 종료할 때 return 보다는 pthread_exit 를 사용하는 것이 더 좋다!

(void * thr_fn1 을 void thr_fn1 로 잘못썻다가 계속 반환값을 이상한 값으로 받아오는 

 오류가 있었다. 스레드 종료값 넘겨줄 때는 pthread_exit가 더 좋은듯 )



예제코드

#include <pthread.h>

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>



void * thr_fn1(void *arg)

{

    printf("thread 1 returning \n");

    return ((void *) 1);

}


void * thr_fn2(void *arg)

{

    printf("thread 2 exiting \n");

    pthread_exit((void *)2);

}



int main(void)

{

    int err;

    pthread_t tid1, tid2;

    void *tret;


    err = pthread_create(&tid1, NULL, thr_fn1, NULL);

    if (err != 0 )

    {

        printf("can't create thread 1: %s\n", strerror(err));

        exit(err);

    }


    err = pthread_create(&tid2, NULL, thr_fn2, NULL);

    if(err != 0 )

    {

        printf("can't create thread 2 : %s\n", strerror(err));

        exit(err);

    }

    err = pthread_join(tid1, &tret);

    if (err != 0 )

    {

        printf("can't join with thread 1: %s\n", strerror(err));

        exit(err);

    }

    printf("thread 1 exit code %d\n", (int)tret);


    err = pthread_join(tid2, &tret);

    if ( err != 0 )

    {

        printf("can't jon with thread 2: %s\n", strerror(err));

        exit(err);

    }

    printf("thread 2 exit code %d\n", (int)tret);

    exit(0);

}


$ gcc 11-3.c -o 11-3 -lpthread

$ 11-3

thread 1 returning

thread 2 exiting

thread 1 exit code 1

thread 2 exit code 2



* 참고 : 유닉스 고급 프로그래밍 11-3 예제 참고

Posted by Triany
2014. 6. 12. 11:17

html 띄어쓰기 표현( 스페이스 표현 ) nbsp; ensp; emsp;


&nbsp; - 스페이스 
&ensp; - 스페이스
&emsp; - 큰스페이스


'web > html' 카테고리의 다른 글

[HTML Number] &#34; &quot; 따옴표( double quotes )  (0) 2014.05.22
[css] 테이블 선 스타일(border-style)  (0) 2014.05.19
Posted by Triany
2014. 6. 11. 14:43

* 구글나우, 대중교통에서 목적지 도착시 알려주는 '알람' 기능 도입

http://media.daum.net/economic/others/newsview?newsid=20140610091305024

 구글 나우는 대중교통을 이용할 때 집이나 직장에 도착하기 직전 알람을 울리는 기능을 추가했다.

 한편 앞서 구글은 구글 나우에 주차 위치를 알려주는 서비스를 선보인 바 있다. 이는 주차 위치를 몰라 헤매는 경우에 구글이 스마트폰으로 차량의 위치를 찾아주는 서비스다. 이는 스마트폰 모션 센서를 이용한 것으로 사용자의 위치정보를 분석해 차를 타고 있다가 걷는 상태로 바뀌는 장소를 주차한 곳으로 인지해 구글 나우 카드에 기록한다. 기록된 내용은 언제든 열어서 확인할 수 있게 했다.


http://media.daum.net/digital/software/newsview?newsid=20140507095213629

구글은 안드로이드용 모바일 애플리케이션 `구글 나우`를 통해 사용자가 검색한 물품을 구입할 수 있는 매장이 근처에 있을 경우 알려주는 기능을 추가한다.

예를 들면 스마트폰 사용자가 `장화`를 검색했을 경우, 구글 나우는 이를 기억하고 있다가 장화를 판매하는 상점 주위에 사용자가 다가가면 상점의 판매 내역을 알려주는 방식이다.


http://www.bloter.net/archives/190924

구글나우, 주차 위치도 알려준다





* 페이스북의 '가상화폐 실험'

http://www.hankyung.com/news/app/newsview.php?aid=2014060853541

페이스북은 게시물 저작자에게 가상화폐를 줄 수 있는 앱인 ‘도기 티핑앱’과 ‘멀티코인 티핑앱’ 2종을 지난 5일 승인했다. 플러그인 방식의 이들 앱을 이용하면 마음에 드는 콘텐츠에 단순히 ‘좋아요’를 누르는 것에 그치지 않고 저작자에게 일정액의 가상화폐를 전송할 수 있다. 도기코인 등 비트코인과 비슷한 가상화폐 14종을 사용한다. 소셜네트워크서비스(SNS)와 가상화폐의 결합이다.

==> 비트코인 

http://terms.naver.com/entry.nhn?docId=2045013&cid=515&categoryId=1164

    [Tour World] SF영화처럼…비트코인 들고 홍콩여행 도전

번거로운 달러 환전 대신 전자 화폐로 먹고 자고 놀고

http://news.mk.co.kr/newsRead.php?year=2014&no=867381






* 잡플래닛 -> 글래스도어를 본떠 만든 이 사이트는 오픈한 지 두 달 만에 이용자 수가 137만명을 넘었다. 

http://news.naver.com/main/read.nhn?mode=LSD&mid=sec&sid1=101&oid=023&aid=0002766943





*'카카오 지갑'에 청년들 분개하는 이유는?

카카오톡 친구끼리 소액을 충전해 송금을 할 수 있는 '뱅크월렛 카카오' 서비스가 곧 출시될 것으로 알려지면서 비슷한 서비스를 이미 제공하고 있는 벤처업계가 울상이다.

한 모바일 청첩장서비스 관계자는 "카카오가 축의금과 조의금을 주요 수익원으로 보고 있다"면서 "3500만명의 유저를 앞세워 카카오가 시장에 진입하면 이제 막 시장에 안착한 스타트업이 피해를 볼 수밖에 없다"고 말했다.

http://media.daum.net/economic/finance/newsview?newsid=20140427080006084





* 식중독 추적에 사용되는 SNS

http://newspeppermint.com/2014/05/28/foodborne/



Posted by Triany
2014. 6. 10. 18:17

pthread.h를 include했는데도 undefined reference to `pthread_create' 에러날때는

-lpthread 를 gcc 옵션에 주어 컴파일 하면 okay!

 

gcc -o 11-2 11-2.c -lpthread

 

Posted by Triany
2014. 6. 9. 18:51

가장 크기가 큰 디렉토리

du -S | sort -n

 

 

Posted by Triany
2014. 6. 9. 11:28

아파치 (Apache) httpd 실행 시

./apachectl start

"httpd: bad user name daemon"

이런 에러가 뜰 때

 

conf/httpd.conf 파일을 열어 daemon을 존재하는 계정으로 변

User daemon

Group daemon

Posted by Triany
2014. 5. 30. 15:29

php에서 web url이용하여 xml파싱하기


아래 설정 안해놔서 반나절 동안 삽질하였다. ㅠ_ㅜ

php.ini에서

extension=php_soap.dll
extension=php_sockets.dll
extension=php_xmlrpc.dll
extension=php_curl.dll
extension=php_openssl.dll



만약 아래 에러가 나오면! allow_url_fopen을 on으로 바꿔준다!

Warning: simplexml_load_file() [function.simplexml-load-file]: URL file-access is disabled in the server configuration in

allow_url_fopen = Off

-> allow_url_fopen = On


기상청 예제로, 참고해 볼수 있도록 소스를 남겨두었다.

http://www.kma.go.kr/XML/weather/sfc_web_map.xml

<html>

<head>

</head>

<body>

<?

$url = "http://www.kma.go.kr/XML/weather/sfc_web_map.xml";


$xml = @simplexml_load_file($url);

$weather = $xml->weather;

foreach( $weather->local as $local)

{

echo "<b>".$local."<br></b>";

foreach($local->attributes() as $a => $b) {

    echo "$a=$b<br>";

}

echo "----------------------------<br>";

}

?>


</body>

</html>

결과>>>>



Posted by Triany
2014. 5. 30. 11:28

1. 디지털 파놉티콘, 그 이름 ‘페이스북’

영국 유력 일간지 ‘가디언’의 기자 앤드류 브라운은 “페이스북은 당신의 친구가 아니다”고 말했다. 그의 말이 거짓은 아닌 듯하다. 페이스북에 당신의 친구가 있을지 모르지만 페이스북은 당신의 친구가 될 수 없다. 페이스북은 당신의 일거수일투족을 데이터 형태로 수집해 수익을 만들어내는 디지털 공장이다. 너무 과격한 해석일까?

- 페이스북은 5월21일 오디오 인식 기능을 곧 제공할 것이라고 발표했다.

- 페이스북의 안면인식 기술

- 페이스북 광고주는 당신의 정보 탐낸다

- NSA, 페이스북 감청을 항상 노린다

<<파놉티콘>>

파놉티콘의 어원은 그리스어로 '모두'를 뜻하는 'pan'과 '본다'를 뜻하는 'opticon'을 합성한 것으로

벤담이 소수의 감시자가 모든 수용자를 자신을 드러내지 않고 감시할 수 있는 형태의 감옥을 제안하면서 이 말을 창안했다.

출처 : http://ko.wikipedia.org/wiki/%ED%8C%8C%EB%86%89%ED%8B%B0%EC%BD%98

출처 : http://www.bloter.net/archives/194211

 

 

 

2.지상은 비좁아…대기권 바깥으로 눈 돌리는 구글

구글의 행보를 보면, 사업 영역을 지구 대기권 밖에서 찾으려는 것처럼 보인다. 구글은 최근 미국의 위성사진 전문 스타트업 스카이박스이미징 인수를 타진 중인 것으로 알려졌다. 위성통신 전문업체의 인력이 구글에 합류한 것도 최근의 일이다. 전세계 광고, 검색 시장을 모두 움켜쥔 구글이 지구 밖으로 눈을 돌려 사업 기회를 엿보고 있다.

위성 기술 업체·전문가 끌어안기 잰걸음

통신∙지도에 위성 기술 활용

구글이 지난 2월 발표한 ‘프로젝트 룬(Loon)’이 대표적이다. 인터넷 통신 장비를 갖춘 열기구를 하늘에 띄워, 인터넷 인프라가 없는 지역에 있는 사용자가 무선으로 인터넷에 접속할 수 있도록 돕는 기술이다. 열기구는 태양열로 움직인다. 열기구가 떠 있는 고도도 보통 여객기가 다니는 높이보다 2배 정도 높다. 땅이 넓어 통신 인프라가 부족한 지역이나 이제 막 인터넷이 보급되기 시작하는 개발도상국이 프로젝트 룬의 혜택을 받을 것으로 보인다. 지상에 새 인터넷 인프라를 마련하는 것보다 비용과 시간을 아낄 수 있기 때문이다.

출처 :  http://www.bloter.net/archives/194033

 

 

Posted by Triany
2014. 5. 29. 15:33

[자바스크립트][예제] 간단한 password 체크 프로그램

=> 아주 간단한 예제, 예외처리 해서 써야 하는 부분들은 많지만, 간단히 password체크 해 볼 수 있다!






<html>

<head>

<script language="javascript">

function passwordCheckk()

{

var password = document.getElementById("password").value;

var passwordCheck = document.getElementById("passwordCheck").value;


if ( passwordCheck == "")

                        {  

                               document.getElementById("passwordCheckText").innerHTML = "" } 

                         else if ( password != passwordCheck )

{

document.getElementById("passwordCheckText").innerHTML = "<b><font color=red size=5pt> Not Ok PW. </font></b>"

}

else

{

document.getElementById("passwordCheckText").innerHTML = "<b><font color=red size=5pt> Ok PW. </font></b>"

}

}

</script>

</head>

<body>

<table border=1>

<tr style="border-left-style:dashed;border-right-style:dashed">

<td>

패스워드

</td>

<td colspan="2">

<input type="password" id="password" name="pw"><br>

</td>

</tr>

<tr style="border-left-style:dashed;border-right-style:dashed">

<td>

패스워드체크

</td>

<td>

<input type="password" id="passwordCheck" name="pw" onkeyup="passwordCheckk()"><br>

</td>

<td id="passwordCheckText" width=100>

</td>

</tr>

</table>

</body>

</html>





Posted by Triany