- 1 pthread ÀÌ¿ëÇÏ¿© ¾²·¹µå »ý¼º
- 2 mutex¸¦ ÀÌ¿ëÇÏ¿©, critical sectionÀÇ µ¥ÀÌÅÍ µ¿±âÈ
- 3 signalÀ» ÀÌ¿ëÇÏ¿© ¾²·¹µå°£ ½ÅÈ£º¸³»±â
1 pthread ÀÌ¿ëÇÏ¿© ¾²·¹µå »ý¼º #
#include <pthread.h>
void *threadfunc(void *arg)
{
...
}
int main()
{
int n, status;
pthread_t threadid;
n = pthread_create(&threadid, NULL, threadfunc, NULL);
while(1){
// Main Thread
}
return 0;
}
2 mutex¸¦ ÀÌ¿ëÇÏ¿©, critical sectionÀÇ µ¥ÀÌÅÍ µ¿±âÈ #
#include <pthread.h>
pthread_mutex_t lock;
unsigned criticalvalue = 0;
int WriteData(const int value)
{
pthread_mutex_lock(&lock);
criticalvalue = value;
pthread_mutex_unlock(&lock);
return 0;
}
int ReadData(void)
{
pthread_mutex_lock(&lock);
cout << "Data : " << criticalvalue << "\n";
pthread_mutex_unlock(&lock);
return 0;
}
3 signalÀ» ÀÌ¿ëÇÏ¿© ¾²·¹µå°£ ½ÅÈ£º¸³»±â #
#include <pthread.h>
#include <iostream>
#include <signal.h>
using namespace std;
bool is_data = false;
unsigned criticalvalue = 0;
pthread_mutex_t lock;
void sig_isdata(int signo)
{
is_data = true;
}
int ReadData(void)
{
pthread_mutex_lock(&lock);
cout << "Data : " << criticalvalue << "\n";
pthread_mutex_unlock(&lock);
return 0;
}
int WriteData(const int value)
{
pthread_mutex_lock(&lock);
criticalvalue = value;
pthread_mutex_unlock(&lock);
return 0;
}
void *threadfunc(void *arg)
{
int n = 1;
while(1)
{
n++;
if(n%1000000 == 0){
WriteData(n);
kill(getpid(), SIGUSR1);
}
}
}
int main()
{
int n;
pthread_t threadid;
signal(SIGUSR1, (void (*)(int))sig_isdata);
pthread_mutex_init(&lock, NULL);
n = pthread_create(&threadid, NULL, threadfunc, NULL);
while(1){
if(is_data){
ReadData();
is_data = false;
}
}
pthread_join(threadid, (void **) &status);
return 0;
}