include pthread h include stdio h int global
Умножение вектора на вектор (управление потоками и мьютексы) #include <pthread. h> #include <stdio. h> int global. Res = 0; int v 1[100], v 2[100]; int ids[4] = {0, 1, 2, 3}; pthread_t thrs[4]; pthread_mutex_t mutex; void* prod(void* me) { int offset = *((int*)me); offset *= 25; int res = 0; for(int i = offset; i<offset+25; i++) res += v 1[i]*v 2[i]; pthread_mutex_lock(&mutex); global. Res += res; pthread_mutex_unlock(&mutex); } int main() { //. . . инициализация массивов thread_attr_t attrs; if(0!=pthread_attr_init(&attrs, NULL)) { abort() }; pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex, NULL); for(int i = 0; i<4; i++) pthread_create(&thrs[i], &attrs, prod, &ids[i]); pthread_attr_destroy(&attrs); for(int i = 0; i<4; i++) pthread_join(thrs[i], NULL); return 0; }
Ошибочная передача параметров int t; pthread_t thrs[NUM_THREADS]; for(t=0; t<NUM_THREADS; t++) {. . . pthread_create(&threads[t], NULL, thread. Func, (void *) &t); . . . }
Условные переменные ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ pthread_mutex_t mutex; pthread_cond_t cond; int counter = 0; ПОТОК НОМЕР 1 pthread_mutex_lock(&mutex); if(counter!=critical. Value) pthread_cond_wait(&cond, &mutex); process. Critical. Value(); pthread_mutex_unlock(); ПОТОК НОМЕР 2 do {. . . pthread_mutex_lock(&mutex); do. Something. With(&counter); if(counter==critical. Value) pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); . . . }while(. . . );
Компиляция программ, использующих POSIX Threads API gcc filename. c -lpthread
Размер стека: обратить внимание Размер стека потока по умолчанию зависит от реализации POSIX Threads API и должен быть настроен по потребностям приложения с помощью функций: pthread_attr_getstacksize (attr, stacksize) pthread_attr_setstacksize (attr, stacksize) pthread_attr_getstackaddr (attr, stackaddr) pthread_attr_setstackaddr (attr, stackaddr)
Источники дополнительных сведений • POSIX Threads Programming tutorial https: //computing. llnl. gov/tutorials/pthreads • International Organization for Standardization, Geneva. Information technology --- Portable Operating System Interface (POSIX) --- Part 1: System Application Program Interface (API) [C Language], December 1996. • The Open Group Base Specifications Issue 6 IEEE Std 1003. 1, 2004 Edition. Follow the links. http: //www. opengroup. org/onlinepubs/009695399/mindex. html • Потоки в UNIX. http: //www. opengroup. org/onlinepubs/007908799/xsh/threads. html • Лабораторная работа http: //ssdonline. sscc. ru/korneev/Lab 9/pthreads 1. html • Manual pages. В командной строке UNIX набрать: man <имя фунции>.
- Slides: 18