Reputation: 11
I am newly starting using Linux in Ubuntu and am trying to code a multi-threading merge sort but some kind of errors are showing on Windows terminal.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
struct Params
{
int *start;
size_t len;
int depth;
};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void *merge_sort_thread(void *pv);
void merge(int *start, int *mid, int *end)
{
int *res = malloc((end -start)*sizeof(*res));
int *lhs = start, *rhs = mid, *dst = res;
while (lhs != mid && rhs != end)*dst++ = (*lhs <= *rhs) ? *lhs++ : *rhs++;
while (lhs != mid)*dst++ = *lhs++;
while (rhs != end)*dst++ = *rhs++;
memcpy(start, res, (end -start)*sizeof(*res));free(res);
}
void merge_sort_mt(int *start, size_t len, int depth)
{
if (len < 2)return;
if (depth <= 0 || len < 4)
{
merge_sort_mt(start, len/2, 0);
merge_sort_mt(start+len/2, len-len/2, 0);
}
else{
struct Params params = { start, len/2, depth/2 };
pthread_t thrd;pthread_mutex_lock(&mtx);
printf("Starting subthread...\n");
pthread_mutex_unlock(&mtx);
pthread_create(&thrd, NULL, merge_sort_thread, ¶ms);
merge_sort_mt(start+len/2, len-len/2, depth/2);
pthread_join(thrd, NULL);
pthread_mutex_lock(&mtx);
printf("Finished subthread.\n");
pthread_mutex_unlock(&mtx);
}
merge(start, start+len/2, start+len);
}
void *merge_sort_thread(void *pv)
{
struct Params *params = pv;
merge_sort_mt(params->start, params->len, params->depth);
return pv;
}
void merge_sort(int *start, size_t len)
{
merge_sort_mt(start, len, 4);
}
int main()
{
static const unsigned int N = 2048;
int *data = malloc(N * sizeof(*data));
unsigned int i;
srand((unsigned)time(0));
for (i=0; i<N; ++i)
{
data[i] = rand() % 1024;
printf("%4d ", data[i]);
if ((i+1)%8 == 0)
printf("\n");
}
printf("\n");
merge_sort(data, N);
for (i=0; i<N; ++i)
{
printf("%4d ", data[i]);
if ((i+1)%8 == 0)
printf("\n");
}
printf("\n");
free(data);
return 0;
}
Here, is the .c code of multithreadind but not complete the program due to errors. Here below, is the errors..
/tmp/ccTNp3Yz.o: In function `merge_sort_mt':
OS.c:(.text+0x213): undefined reference to `pthread_create'
OS.c:(.text+0x269): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
If any library or any correction in code please tell and please add some important libraries which is usually used in terminal like sudo
Upvotes: 1
Views: 126
Reputation: 1401
As was stated at the comment above, you need to link your program with pthread library.
add -lpthread to your link command.
Upvotes: 1