Семафоры-счетчики POSIX Программирование с использованием POSIX thread library.

Slides:



Advertisements
Similar presentations
Linux Serial Programming for POSIX Operating Systems
Advertisements

For(int i = 1; i
Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class.
Threads Relation to processes Threads exist as subsets of processes Threads share memory and state information within a process Switching between threads.
File and I/O system calls int open(const char* path, int flags, mode_t modes) int creat(const char *path, mode_t mode) ssize_t read(int fd, void *buf,
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
Pthread and POSIX.1c Threads. What’s A Thread? (Review) Recall that a process is a complete computational entity, including –credentials, –resources and.
Другие примитивы синхронизации Программирование с использованием POSIX thread library.
CS 311 – Lecture 09 Outline Introduction to Systems programming – System calls – Categories of system calls Error Management System calls File Handling.
PHP как язык программирования. Типы данных логические величины int, integer – целые числа real, double, float – вещественные числа string – строки array.
Управление нитями Программирование с использованием POSIX thread library.
CS 311 – Lecture 10 Outline Review open() and close() Difference between fopen() and open() File management system calls – read() – write() – lseek() –
Posix Message Queues Courtesy of W. Richard Stevens Unix Network Programming Volume 2: Interprocess Communication.
Демидов А.В г. Операционные системы Лекция 4 Работа с файлами.
Project 2 Hints. pthread_create SYNOPSIS #include int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*start_routine)(void *), void.
Advanced Programming in the UNIX Environment Hop Lee.
0 + 0= = = = 10 Арифметические операции во всех позиционных системах счисления выполняются по одним и тем же хорошо известным вам правилам.
02/02/2004CSCI 315 Operating Systems Design1 Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook Operating.
Обработка исключений в C# Единая техника обнаружения ошибок времени выполнения и передачи информации о них.
POSIX: Files Introduction to Operating Systems: Discussion 1 Read Solaris System Interface Guide: Ch. 5.1 Basic File I/O.
Chapter 4: Threads Adapted to COP4610 by Robert van Engelen.
Operating Systems Chapter 5 Threads. Benefits Responsiveness Resource Sharing Economy Utilization of MP Architectures.
Solutions to the first midterm COSC 4330/6310 Summer 2013.
Lecture 2 Linux Basic Commands,Shell and Make September 8, 2015 Kyu Ho Park.
The Third Assignment COSC 4330/6310 Spring Implementing delays To be able to test the semaphores, we must run the program in real time To be able.
2.3 InterProcess Communication (IPC)
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
What is a thread? process: an address space with 1 or more threads executing within that address space, and the required system resources for those threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Linux Programming –Threads CS Threads Review Threads in the same address space –share everything in the address space –lighter than process –no.
Chapter 6 Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th Edition, Feb 8, 2005 Module 6: Process Synchronization.
Saint Petersburg, 2011 Java Lecture Generics. Quiz ArrayList lst = new ArrayList(); Collection c = lst; lst.add("one"); lst.add(“two"); lst.add(“three");
Lecture 5 Process, Thread and Task September 22, 2015 Kyu Ho Park.
CSC Advanced Unix Programming, Fall, 2008 Monday, November 24 POSIX threads (pthreads)
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 11: Thread-safe Data Structures, Semaphores.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 12: Thread-safe Data Structures, Semaphores.
Announcements. Cooperating Processes  Operating systems allow for the creation and concurrent execution of multiple processes & threads  eases program.
File I/O open close lseek read and write – unbuffered I/O dup and dup2.
Print Row Function void PrintRow(float x[ ][4],int i) { int j; for(j=0;j
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
CISC2200 Threads Fall 09. Process  We learn the concept of process  A program in execution  A process owns some resources  A process executes a program.
Using System Calls (Unix) Have to tell compiler (if C/C++) where to find the headers, etc. – i.e., the “include” files May have to tell compiler where.
Web Server Architecture Client Main Thread for(j=0;j
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
1 CMSC Laundry List P/W/F, Exam, etc. Instructors: HSG, HH, MW.
CS 311/350/550 Semaphores. Semaphores – General Idea Allows two or more concurrent threads to coordinate through signaling/waiting Has four main operations.
CSC Advanced Unix Programming, Fall, 2008 Monday, December 1 Thread local storage, POSIX:SEM semaphores and POSIX:XSI IPC.
Lecture 2 Linux Basic Commands,Shell and Make
Synchronization and Semaphores
CS 537 – Introduction to Operating Systems
C Threads and Semaphores
Linux Thread Programming
Process Synchronization
סמפורים.
ريسه ها Threads اسلايدهاي فصل چهارم کتاب سيلبرشاتز
Concurrent Programming
Synchronization and Semaphores
Operating System Concepts
CSE 333 – Section 3 POSIX I/O Functions.
CSE 333 – Section 3 POSIX I/O Functions.
Synchronization.
Synchronization.
Lab #9 Semaphores Operating System Lab.
Presentation transcript:

Семафоры-счетчики POSIX Программирование с использованием POSIX thread library

Семафоры-счетчики POSIX Realtime Extension (1003.1b- 1993/1003.1i-1995) Сборка в Solaris требует ключа –lrt В Linux включены в libpthread.so

Неименованные семафоры cc [ flags] file –lrt [ libraries ] #include int sem_init(sem_t *sem, int pshared, unsigned int value); int sem_destroy(sem_t *sem);

Операции над семафорами cc [ flags] file –lrt [ libraries ] #include int sem_post(sem_t *sem); int sem_wait(sem_t *sem); int sem_trywait(sem_t *sem);

sem_getvalue cc [ flags] file –lrt [ libraries ] #include int sem_getvalue( sem_t *restrict sem, int *restrict sval);

Применение – задача производитель-потребитель void thread1() { while(1) { sem_wait(&a); print(…); sem_post(&b); } void thread2() { while(1) { sem_wait(&b); print(…); sem_post(&a); } sem_init(&a, 0, 0); sem_init(&b, 0, 1);

Именованные семафоры cc [ flags] file –lrt [ libraries ] #include sem_t *sem_open(const char *name, int oflag, /* unsigned long mode, unsigned int value */...);

sem_open(3RT) Открывает или создает именованный семафор. Флаги – O_CREAT и O_EXCL, аналогичны одноименным флагам open(2) При использовании O_CREAT необходимо передать еще два параметра – маску прав доступа и начальное значение семафора

sem_close(3RT) cc [ flags] file –lrt [ libraries ] #include int sem_close(sem_t *sem);

sem_close(3RT) Закрывает семафор Неявный sem_close происходит при exit(2), exec(2)

Именованные семафоры Всегда разделяемые (доступны для межпроцессного взаимодействия) Должны закрываться sem_close(3RT) Набор операций тот же, что и над неименованным семафором (sem_post(3RT), sem_wait(3RT), sem_trywait(3RT), sem_getvalue(3RT)) Имя должно начинаться с ‘/’ Имена могут (но не обязаны) быть видны в файловой системе. В Solaris 10 не видны Уничтожаются при помощи sem_unlink(3RT)

sem_unlink cc [ flags] file –lrt [ libraries ] #include int sem_unlink(const char * name);

sem_unlink Уничтожает имя семафора Семафор уничтожается, когда все процессы, использовавшие его, исполнят sem_close(3rt), exit(2) или exec(2) Sem_unlink не ожидает уничтожения семафора