- 论坛徽章:
- 1
|
运行断错误
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
struct arg_pthread
{
FILE *fp;
int num;
pthread_mutex_t mutex;
};
void *thread(void *arg)
{
struct arg_pthread *arg_t = (struct arg_pthread *)arg;
int run;
FILE *fp = arg_t->fp;
if (pthread_mutex_lock(&(arg_t->mutex)) != 0)
{
perror("pthread_mutex_lock ");
return NULL;
}
for (run=1; run<4; run++) {
fprintf(fp, "In thread%d run %d\n", arg_t->num, run);
}
unlock:
if (pthread_mutex_unlock(&(arg_t->mutex)) != 0)
{
perror("pthread_mutex_unlock ");
goto unlock;
}
}
int main()
{
FILE *readf = NULL;
pthread_t myth1, myth2;
struct arg_pthread *arg;
readf = fopen("./testfile", "w+");
if (readf == NULL)
{
perror("fopen ");
exit(-1);
}
arg->fp = readf;
arg->num = 1;
if (pthread_mutex_init(&(arg->mutex), NULL) != 0)
{
perror("mutex init ");
fclose(readf);
exit(-1);
}
if (pthread_create(&myth1, NULL, thread, (void *)arg) != 0)
{
perror("pthread_create1 ");
fclose(readf);
exit(-1);
}
pthread_join(myth1, NULL);
arg->num = 2;
if (pthread_create(&myth2, NULL, thread, (void *)arg) != 0)
{
perror("pthread_create2 ");
fclose(readf);
pthread_cancel(myth1);
exit(-1);
}
pthread_join(myth2, NULL);
pthread_mutex_destroy(&(arg->mutex));
fclose(readf);
exit(0);
}
|
|
|