- /*
- * Finden Sie in Task3.c den Deadlock.
- * Beheben Sie den Deadlock.
- * Ändern Sie das Programm so ab, dass es kompilierbar und ausführbar ist.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- struct List{
- int data;
- struct List* next;
- };
- int popFirst(struct List** _list) {
- if(*_list == NULL || *_list == (struct List*)-1)
- return 0;
- int val = (*_list)->data;
- struct List* t = (*_list)->next;
- free(*_list);
- *_list = t;
- return val;
- }
- void put(struct List** _list, int _data) {
- if(*_list == NULL || *_list == (struct List*)-1) {
- *_list = (struct List*)malloc(sizeof(struct List));
- (*_list)->data = _data;
- (*_list)->next = NULL;
- } else {
- put(&((*_list)->next), _data);
- }
- }
- struct List* MaterialQueue = (struct List*)-1;
- int ElementCount = 0;
- pthread_mutex_t QueueLock, CountLock;
- void* producerFnc(void* in) {
- srand(1234);
- int counter = 0;
- while( 1 && counter < 100) {
- pthread_mutex_lock(&QueueLock);
- pthread_mutex_lock(&CountLock);
- put(&MaterialQueue, rand());
- ElementCount++;
- counter++;
- pthread_mutex_unlock(&CountLock);
- pthread_mutex_unlock(&QueueLock);
- }
- return 0;
- }
- void* workerFnc(void* _in) {
- int id = ((int*)_in)[0];
- int element;
- long sum = 0;
- while( 1 && MaterialQueue != NULL) {
- pthread_mutex_lock( &QueueLock );
- pthread_mutex_lock( &CountLock );
- if(ElementCount > 0) {
- element = popFirst(&MaterialQueue);
- ElementCount--;
- }
- pthread_mutex_unlock( &CountLock );
- pthread_mutex_unlock( &QueueLock );
- printf("%d: %d\n", id, element);
- usleep(5);
- }
- return 0;
- }
- int main(int argc, char** argv) {
- pthread_t producer;
- pthread_t worker[15];
- pthread_create( &producer, 0, producerFnc, 0 );
- for( int i = 0; i < 15; i++ ) {
- pthread_create( &worker[i], 0, workerFnc, &i);
- }
- pthread_join( producer, 0 );
- for( int i = 0; i < 15; i++ ) {
- pthread_join( worker[i], 0 );
- }
- return 0;
- }
[text] test
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new: