Skip to content
Snippets Groups Projects
Commit ddaefabb authored by JieunYoon's avatar JieunYoon
Browse files

Add thread practice

parent 3aea1605
No related branches found
No related tags found
No related merge requests found
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
int d1=10, d2;
void * hello_thread(void *arg)
{
int i=200;
printf("Hello_Thread Start(d1:%d, d2:%d, i:%d)!!\n", d1,d2,i);
for(i=1; i<=(int)arg; i++) {
printf("Hello_Thread_%d!!\n", i);
d1++;
d2++;
sleep(1);
}
printf("Hello_Thread End(d1:%d, d2:%d, i:%d)!!\n", d1,d2,i);
//return arg;
pthread_exit(arg);
}
int main(void)
{
pthread_t tid;
int status;
int i=100;
pthread_attr_t attr; //속성은 우리가 채우는 것이다. 값을 할당하고 넘기는 것이 의미가 있다.
printf("Main_Thread Start(d1:%d, d2:%d, i:%d)!!\n", d1,d2,i);
status = pthread_create(&tid, NULL, hello_thread, (void*)15);//주소를 넘긴다. 속성을 받지 않을 거면 NULL.
if(status != 0) {
perror("thread create");
exit(1);
}
for(i=1; i<=5; i++) {
printf("Main_Thread_%d!!\n", i);
sleep(1);
}
printf("Main_Thread End(d1:%d, d2:%d, i:%d)!!\n", d1,d2,i);
pthread_exit(NULL); //커널에게 내 메모리를 access하는 녀석이 있다면 메모리를 해지하지 말아라.
return 0;
}
\ No newline at end of file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <sys/syscall.h>
void * thread_function(void *);
int Counter=0;
#ifndef NOMUTEX
.... mutex_id;
#endif
int main(void)
{
pthread_t tid1, tid2;
void *thread_result;
#ifndef NOMUTEX
if(________(&mutex_id, NULL) != 0){
perror("pthread_mutex_init");
exit(errno);
}
#endif
if(_______(&tid1, NULL, thread_function, "thread1")!=0) {
perror("pthread_create");
exit(1);
}
if(_______(&tid2, NULL, thread_function, "thread2")!=0) {
perror("pthread_create");
exit(1);
}
if(_______(tid1, &thread_result)!=0) {
perror("pthread_join");
exit(1);
}
if(_______(tid2, &thread_result)!=0) {
perror("pthread_join");
exit(1);
}
#ifndef NOMUTEX
___________(&mutex_id);
#endif
printf(" thread result : %s\n", (char *) thread_result);
return 0;
}
void * thread_function(void * arg)
{
int temp;
int i, j;
char buffer[80];
printf("thread_function called\n");
for(i=0; i<8; i++) {
#ifndef NOMUTEX
_________(&mutex_id);
#endif
sprintf(buffer, "%s: CountRelay: from %d to ", (char*)arg, Counter);
write(1, buffer, strlen(buffer));
temp=Counter;
temp = temp+1;
// delay
for(j=0; j<5000000; j++);
Counter=temp;
sprintf(buffer, "%d\n", Counter);
write(1, buffer, strlen(buffer));
#ifndef NOMUTEX
__________(&mutex_id);
#endif
}
// getchar();
_______("thread end");
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment