Академический Документы
Профессиональный Документы
Культура Документы
Томск – 2008
ЦЕЛЬ РАБОТЫ: Ознакомиться с подсистемой управления потоками в
операционной системе Unix и основными программными средствами для
создания, управления и удаления потоков.
Текст программы:
#include <pthread.h>
#include <fstream.h>
#include <semaphore.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t lock;
ofstream out;
int main(){
out.open("outfile.txt");
pthread_mutex_init(&lock, NULL);
pthread_t threadA;
pthread_t threadB;
pthread_create(&threadA,NULL,&first,NULL);
pthread_create(&threadB,NULL,&second,NULL);
pthread_join(threadA,NULL);
pthread_join(threadB,NULL);
pthread_mutex_destroy(&lock);
out.close();
Результат выполнения.
Текст программы:
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int count;
sem_t sem;
sem_wait(&sem);
sem_post(&sem);
return NULL;
int main(){
sem_init(&sem,0,0);
sem_post(&sem);
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,&funck,(void*)1);
pthread_create(&thread2,NULL,&funck,(void*)-1);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
sem_destroy(&sem);
return 0;
}
Результат выполнения.
Текст программы:
#include <pthread.h>
#include <fstream.h>
#include <iostream.h>
#include <stdlib.h>
int zn;
pthread_mutex_t mutex;
pthread_cond_t cond;
int main()
{
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_t addT;
pthread_create(&addT,NULL,add,NULL);
pthread_t minusT;
pthread_create(&minusT,NULL,minus,NULL);
pthread_join(addT, NULL);
pthread_cancel(minusT);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
pthread_cond_signal(&cond);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
}
pthread_mutex_lock(&mutex);
printf("%i",zn);
printf(" ");
pthread_cond_signal(&cond);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
}
Результат выполнения.
Вывод:
Использование потоков может быть хорошим инструментом при
необходимости обеспечить одновременное выполнение нескольких действий,
в частности позволяет избежать простоев при вводе данных, однако
усложняет программу и вызывает во многих случаях необходимость
синхронизации при обращении к общим данным.