Skip to content

Commit

Permalink
complete assignment 4-1
Browse files Browse the repository at this point in the history
  • Loading branch information
yinwenjie committed Jul 6, 2024
1 parent 0213ad2 commit 45a24e1
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
38 changes: 37 additions & 1 deletion examples/threading/threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,40 @@
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// Optional: use these functions to add debug or error prints to your application
#define DEBUG_LOG(msg,...)
//#define DEBUG_LOG(msg,...) printf("threading: " msg "\n" , ##__VA_ARGS__)
#define ERROR_LOG(msg,...) printf("threading ERROR: " msg "\n" , ##__VA_ARGS__)

typedef struct thread_data thread_data;

void* threadfunc(void* thread_param)
{

// TODO: wait, obtain mutex, wait, release mutex as described by thread_data structure
// hint: use a cast like the one below to obtain thread arguments from your parameter
//struct thread_data* thread_func_args = (struct thread_data *) thread_param;
thread_data* pThreadData = (struct thread_data *) thread_param;
pthread_mutex_t *mutex = pThreadData->mutex;
int wait_to_obtain_ms = pThreadData->wait_to_obtain_ms;
int wait_to_release_ms = pThreadData->wait_to_release_ms;

usleep(wait_to_obtain_ms * 1000);
if (pthread_mutex_lock(mutex) != 0) {
ERROR_LOG("Error: thread lock failed.\n");
pThreadData->thread_complete_success = false;
return thread_param;
}
usleep(wait_to_release_ms * 1000);
if (pthread_mutex_unlock(mutex) != 0) {
ERROR_LOG("Error: thread unlock failed.\n");
pThreadData->thread_complete_success = false;
return thread_param;
}
pThreadData->thread_complete_success = true;

return thread_param;
}

Expand All @@ -28,6 +50,20 @@ bool start_thread_obtaining_mutex(pthread_t *thread, pthread_mutex_t *mutex,int
*
* See implementation details in threading.h file comment block
*/
return false;
thread_data *pThreadData = (thread_data *)malloc(sizeof(thread_data));
memset(pThreadData, 0, sizeof(thread_data));

pThreadData->mutex = mutex;
pThreadData->wait_to_obtain_ms = wait_to_obtain_ms;
pThreadData->wait_to_release_ms = wait_to_release_ms;

if (pthread_create(thread, NULL, threadfunc, (void*)pThreadData) != 0)
{
ERROR_LOG("Error: create thread failed.\n");
free(pThreadData);
return false;
}

return true;
}

3 changes: 3 additions & 0 deletions examples/threading/threading.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ struct thread_data{
* if an error occurred.
*/
bool thread_complete_success;
int wait_to_obtain_ms;
int wait_to_release_ms;
pthread_mutex_t *mutex;
};


Expand Down

0 comments on commit 45a24e1

Please sign in to comment.