Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- RFID
- Linux
- web
- program
- programming_book
- Python
- leadership
- management
- comic agile
- Book review
- France
- Java
- hbase
- Italy
- hadoop
- agile
- Software Engineering
- Programming
- Kuala Lumpur
- QT
- Spain
- history
- Malaysia
- MySQL
- ubuntu
- essay
- psychology
- Book
- django
- erlang
Archives
- Today
- Total
pthread with structure argument 본문
java의 Atomic* 같은 타입이 당연히 없으므로, thread마다 각각 할당해서 넘겨줬음
#include#include #include #include pthread_t threads[5]; int done[5]; void* thread_main(void*); typedef struct { int m_iThreadNum; char m_cChar; long** m_pplValues; } ThreadArg; // http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Beginning/Example_pthread // gcc -o pthread1 pthread1.c -lpthread int main(void) { int i, j, k, rc, status; ThreadArg* ta = (ThreadArg*)malloc(sizeof(ThreadArg) * 5);; printf("pid = %d\n", getpid()); for ( i = 0; i < 5; ++i ) { done[i] = 0; (ta + i)->m_iThreadNum = i; (ta + i)->m_cChar = 'a' + i; (ta + i)->m_pplValues = (long**)malloc(sizeof(long*) * 2); for ( j = 0; j < 2; ++j ) { *((ta + i)->m_pplValues + j) = (long*)malloc(sizeof(long) * 3); for ( k = 0; k < 3; ++k ) *(*((ta + i)->m_pplValues + j) + k) = 100 * (i + 1) + (j + 1) * (k + 1); } printf("ready to give arg: %d %c\n", (ta + i)->m_iThreadNum, (ta + i)->m_cChar); pthread_create(&threads[i], NULL, &thread_main, (void *)(ta + i)); printf("%d, %d\n", i, threads[i]); } for ( i = 4; i >= 0; --i ) { done[i] = 1; rc = pthread_join(threads[i], (void**)&status); if ( rc == 0 ) { printf("Completed join with %d status = %d, %d, %c\n", i, status, (ta + i)->m_iThreadNum, (ta + i)->m_cChar); } else { printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); return -1; } } for ( i = 0; i < 5; ++i ) { for ( j = 0; j < 2; ++j ) { for ( k = 0; k < 3; ++k ) printf("[%d][%d][%d] = %ld\n", i, j, k, *(*((ta + i)->m_pplValues + j) + k)); free(*((ta + i)->m_pplValues + j)); } free((ta + i)->m_pplValues); } free(ta); return 0; } void* thread_main(void* arg) { int i, j; double result = 0.0; ThreadArg* ta = (ThreadArg*)arg; printf("thread {%d} received from %d integer %d\tchar %c\n", ta->m_iThreadNum, getpid(), ta->m_iThreadNum, ta->m_cChar); for ( i = 0; i < 2; ++i ) for ( j = 0; j < 3; ++j ) printf("\t{%d}[%d][%d] = %ld\n", ta->m_iThreadNum, i, j, *(*(ta->m_pplValues + i) + j)); while ( !done[ta->m_iThreadNum] ) { for ( i = 0; i < 1000000; ++i ) { result = result + (double)random(); } printf("thread: %d, result = %e\n", ta->m_iThreadNum, result); } ta->m_iThreadNum = ta->m_iThreadNum + 10; ta->m_cChar = ta->m_cChar + 10; for ( i = 0; i < 2; ++i ) for ( j = 0; j < 3; ++j ) *(*(ta->m_pplValues + i) + j) *= 10; pthread_exit((void*) 0); }
Comments