C 线程同步-何时终止线程?
我正在写一个程序,需要一些输入;目录、文件名和一些标志。该程序的目的是在给定目录中搜索给定文件。在搜索时,如果它找到另一个目录,它将打开该目录并继续在那里搜索。其中一个标志允许用户选择程序用于搜索文件的线程数 目录存储在堆栈中,我遇到的问题是线程之间的同步。我目前正在使用一个带有定时等待条件的互斥锁。这意味着,如果线程等待了一定时间,并且存储目录的堆栈为空,则线程将结束。问题是,当只运行2个线程时,1个线程可能会完成所有工作,即打开400个目录,而另一个线程打开0个目录 所以我的问题是。。。如何以更好的方式同步线程?可能不使用定时等待条件?线程何时终止C 线程同步-何时终止线程?,c,multithreading,synchronization,pthreads,C,Multithreading,Synchronization,Pthreads,我正在写一个程序,需要一些输入;目录、文件名和一些标志。该程序的目的是在给定目录中搜索给定文件。在搜索时,如果它找到另一个目录,它将打开该目录并继续在那里搜索。其中一个标志允许用户选择程序用于搜索文件的线程数 目录存储在堆栈中,我遇到的问题是线程之间的同步。我目前正在使用一个带有定时等待条件的互斥锁。这意味着,如果线程等待了一定时间,并且存储目录的堆栈为空,则线程将结束。问题是,当只运行2个线程时,1个线程可能会完成所有工作,即打开400个目录,而另一个线程打开0个目录 所以我的问题是。。。如何
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <getopt.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <pthread.h>
void search_func(char *path, char *name, int d, int f, int l);
void *thread_func(void *arg);
void push(char *data);
char* pop();
#define MAXLENGTH 1000
#define MAXSIZE 10000
#define WAIT_TIME_SECONDS 0.1
pthread_mutex_t lock;
pthread_cond_t count_threshold_cv;
struct stack
{
char stk[MAXSIZE][MAXLENGTH];
int top;
};
typedef struct stack STACK;
STACK s;
struct arg_keeper {
char **argv;
int argc;
int d;
int f;
int l;
};
int main(int argc, char **argv) {
if(argc < 3) {
fprintf(stderr, "Not enough arguments\n");
return 1;
}
char *xValue = NULL;
int x;
int d = 0;
int f = 0;
int l = 0;
int nrthr = 0;
opterr = 0;
int thread_count = 0;
int directory_exist = 0;
pthread_t tid[1024];
while ((x = getopt(argc, argv, "t:p:")) != -1) {
switch (x) {
case 't':
xValue = optarg;
if (*xValue == 'd') {
d = 1;
} else if (*xValue == 'f') {
f = 1;
} else if (*xValue == 'l') {
l = 1;
}
break;
case 'p':
nrthr = atoi(optarg);
if(nrthr == 0) {
fprintf(stderr, "Invalid thread count\n");
return 1;
}
break;
case '?':
if (isprint (optopt))
fprintf(stderr, "Unknown option '-%c'.\n",
optopt);
return 1;
default:
abort();
}
}
if (argc >= 3) {
int i;
for (i = optind; i < argc - 1; i++) {
directory_exist = 1;
push(argv[i]);
}
}
if(directory_exist == 0) {
fprintf(stderr, "No directories entered\n");
return 1;
}
struct arg_keeper * arg_struct = malloc(sizeof(*arg_struct));
arg_struct->argv = argv;
arg_struct->argc = argc;
arg_struct->d = d;
arg_struct->f = f;
arg_struct->l = l;
if(pthread_mutex_init(&lock, NULL) != 0) {
fprintf(stderr, "Mutex initialisation failed\n");
return 1;
}
if(pthread_cond_init(&count_threshold_cv, NULL) != 0) {
fprintf(stderr, "Condition variable initialisation failed\n");
return 1;
}
while(thread_count < nrthr - 1) {
if(pthread_create(&(tid[thread_count++]), NULL, thread_func,
arg_struct) != 0)
fprintf(stderr, "Can't create thread\n");
}
if(nrthr!=0)
thread_func(arg_struct);
else
thread_func(arg_struct);
int c;
for(c = 0; c < nrthr; c++) {
pthread_join(tid[c], NULL);
}
pthread_mutex_destroy(&lock);
free(arg_struct);
return 0;
}
void *thread_func(void *arg) {
int dirOpened = 0;
struct arg_keeper arg_struct = *(struct arg_keeper *)arg;
char *data;
pthread_mutex_lock(&lock);
struct timespec ts;
struct timeval tp;
while(1) {
gettimeofday(&tp, NULL);
ts.tv_sec = tp.tv_sec;
ts.tv_nsec = tp.tv_usec * 1000;
ts.tv_sec += WAIT_TIME_SECONDS;
if (pthread_cond_timedwait(&count_threshold_cv, &lock, &ts) == ETIMEDOUT) {
if (s.top) {
data = pop();
pthread_cond_signal(&count_threshold_cv);
dirOpened++;
search_func(data, arg_struct.argv[arg_struct.argc - 1], arg_struct.d,
arg_struct.f, arg_struct.l);
}
else
break;
}
}
pthread_mutex_unlock(&lock);
fprintf(stdout, "Thread with id %lu opened %d directories\n",
pthread_self(), dirOpened);
return NULL;
}
void search_func(char *inPath, char *testName, int d, int f, int l) {
char path[PATH_MAX];
strcpy(path, inPath);
struct dirent *pDirent;
DIR *pDir;
struct stat file_info;
if ((pDir = opendir(path)) == NULL) {
fprintf(stderr, "Error:'%s': %s\n", path, strerror(errno));
} else {
int v1;
int v2;
char *str1 = ".";
char *str2 = "..";
char name[PATH_MAX];
strcpy(name, testName);
char testPath[PATH_MAX];
strcpy(testPath, path);
char testPathLast[PATH_MAX];
strcpy(testPathLast, path);
while ((pDirent = readdir(pDir)) != NULL) {
if (strcmp(pDirent->d_name, name) == 0 && d == 0 &&
f == 0 && l == 0) {
if (path[strlen(path) - 1] != '/')
strcat(testPathLast, "/");
strcat(testPathLast, pDirent->d_name);
fprintf(stdout, "%s\n", testPathLast);
}
char testPath2[PATH_MAX];
strcpy(testPath2, testPath);
strcat(testPath2, "/");
strcat(testPath2, pDirent->d_name);
if (lstat(testPath2, &file_info) != 0)
fprintf(stderr, "lstat error2: %s\n",
strerror(errno));
if (d == 1) {
if (strcmp(pDirent->d_name, name)
== 0 && S_ISDIR(file_info.st_mode)) {
if (path[strlen(path) - 1] != '/')
strcat(testPathLast, "/");
strcat(testPathLast, pDirent->d_name);
fprintf(stdout, "%s\n", testPathLast);
}
}
if (f == 1) {
if (strcmp(pDirent->d_name, name)
== 0 && S_ISREG(file_info.st_mode)) {
if (path[strlen(path) - 1] != '/')
strcat(testPathLast, "/");
strcat(testPathLast, pDirent->d_name);
fprintf(stdout, "%s\n", testPathLast);
}
}
if (l == 1) {
if (strcmp(pDirent->d_name, name)
== 0 && S_ISLNK(file_info.st_mode)) {
if (path[strlen(path) - 1] != '/')
strcat(testPathLast, "/");
strcat(testPathLast, pDirent->d_name);
fprintf(stdout, "%s\n", testPathLast);
}
}
v1 = strcmp(pDirent->d_name, str1);
v2 = strcmp(pDirent->d_name, str2);
if ((v1 != 0 && v2 != 0) && S_ISDIR(file_info.st_mode)) {
strcpy(path, testPath);
strcpy(path, testPath);
if (path[strlen(path) - 1] != '/')
strcat(path, "/");
strcat(path, pDirent->d_name);
push(path);
}
}
closedir(pDir);
}
}
void push(char *data)
{
if(s.top == (MAXSIZE - 1)) {
fprintf(stderr, "Stack is full\n");
return;
}
else {
s.top = s.top + 1;
strcpy(&(s.stk[s.top][0]), data);
}
return;
}
char* pop()
{
char *data;
if(s.top == -1) {
fprintf(stderr, "Stack is empty\n");
return NULL;
}
else {
data = s.stk[s.top];
s.top = s.top - 1;
}
return data;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效搜索函数(字符*路径,字符*名称,int d,int f,int l);
void*thread_func(void*arg);
无效推送(字符*数据);
char*pop();
#定义MAXLENGTH 1000
#定义MAXSIZE 10000
#定义等待时间秒0.1
pthread_mutex_t lock;
pthread_cond_t count_threshold_cv;
结构堆栈
{
字符stk[MAXSIZE][MAXLENGTH];
int top;
};
typedef结构堆栈;
堆栈s;
结构参数{
字符**argv;
int-argc;
int d;
int f;
int l;
};
int main(int argc,字符**argv){
如果(argc<3){
fprintf(stderr,“参数不足”\n);
返回1;
}
char*xValue=NULL;
int x;
int d=0;
int f=0;
int l=0;
int nrthr=0;
opterr=0;
int线程计数=0;
int目录_exist=0;
pthread_t tid[1024];
而((x=getopt(argc,argv,t:p:)!=-1){
开关(x){
案例“t”:
xValue=optarg;
如果(*xValue=='d'){
d=1;
}else if(*xValue=='f'){
f=1;
}如果(*xValue=='l'),则为else{
l=1;
}
打破
案例“p”:
nrthr=atoi(optarg);
如果(nrthr==0){
fprintf(stderr,“无效线程计数\n”);
返回1;
}
打破
案例“?”:
如果(iPrint(optopt))
fprintf(标准,“未知选项”-%c.\n“,
光电转换);
返回1;
违约:
中止();
}
}
如果(argc>=3){
int i;
对于(i=optind;iargv=argv;
arg_struct->argc=argc;
arg_struct->d=d;
参数结构->f=f;
参数结构->l=l;
if(pthread\u mutex\u init(&lock,NULL)!=0){
fprintf(stderr,“互斥体初始化失败\n”);
返回1;
}
if(pthread\u cond\u init(&count\u threshold\u cv,NULL)!=0){
fprintf(stderr,“条件变量初始化失败\n”);
返回1;
}
while(线程计数d_name,name)==0&&d==0&&
f==0&&l==0){
if(路径[strlen(路径)-1]!='/'))
strcat(testPathLast,“/”;
strcat(testPathLast,pDirent->d_name);
fprintf(stdout,“%s\n”,testPathLast);
}
char testPath2[PATH_MAX];
strcpy(testPath2,testPath);
strcat(测试路径2,“/
struct work_item {
struct work_item *next;
char path[];
};
struct work {
pthread_mutex_t mutex;
pthread_cond_t cond;
long active;
struct work_item *item;
};
#define WORK_INITIALIZER { \
PTHREAD_MUTEX_INITIALIZER, \
PTHREAD_COND_INITIALIZER, \
0L, NULL }
void *worker_thread(void *work_ptr)
{
struct work *const work = (struct work *)word_ptr;
struct work_item *item;
pthread_mutex_lock(&(work->mutex));
while (1) {
/* If there are no active workers,
nor any work items, we're done. */
if (!work->item && !work->active) {
/* Ensure threads waiting on the condition
variable are woken up, so they quit too. */
pthread_cond_broadcast(&(work->cond));
pthread_mutex_unlock(&(work->mutex));
return NULL;
}
/* No work items left? */
if (!work->item) {
/* Wait for a new one to be produced,
or a worker to notice we're done. */
pthread_cond_wait(&(work->cond), &(work->mutex));
continue;
}
/* Increment active worker count, grab an item,
and work on it. */
work->active++;
item = work->item;
work->item = work->item->next;
item->next = NULL;
/* Unlock mutex while working. */
pthread_mutex_unlock(&(work->mutex));
/*
* TODO: Work on item
*/
pthread_mutex_lock(&(work->mutex));
work->active--;
}
}
struct work_item *temp;
/* TODO: Allocate and initialize temp */
pthread_mutex_lock(&(work->mutex));
temp->next = work->item;
work->item = temp;
pthread_cond_signal(&(work->cond));
pthread_mutex_unlock(&(work->mutex));
#include <sys/sem.h>
int semid;
void push(char *data)
{
pthread_mutex_lock(&lock);
if (s.top == MAXSIZE-1)
fprintf(stderr, "Stack is full\n");
else
strcpy(s.stk[++s.top], data),
semop(semid, &(struct sembuf){0, 1}, 1); // add 1 to "dirs on stack"
pthread_mutex_unlock(&lock);
return;
}
char *pop()
{
char *data;
pthread_mutex_lock(&lock);
if (s.top == -1)
fprintf(stderr, "Stack is empty\n"),
data = NULL;
else
data = strdup(s.stk[s.top--]); // Don't return freed stack slot!
pthread_mutex_unlock(&lock);
return data;
}
// create semaphore set of 2 sems: [0] dirs on stack, [1] threads at work
semid = semget(IPC_PRIVATE, 2, S_IRWXU);
semctl(semid, 0, SETALL, (unsigned short [2]){}); // zero the sem values
while (thread_count < nrthr)
if (pthread_create(&tid[thread_count++], NULL, thread_func, arg_struct))
fprintf(stderr, "Can't create thread\n");
// wait until no more dirs on stack and no more threads at work
semop(semid, (struct sembuf []){{0, 0}, {1, 0}}, 2);
semctl(semid, 0, IPC_RMID); // remove the semaphores, make threads finish
void *thread_func(void *arg)
{
int dirOpened = 0;
struct arg_keeper arg_struct = *(struct arg_keeper *)arg;
char *data;
// wait for work, subtract 1 from dirs on stack and add 1 to threads at work
while (semop(semid, (struct sembuf []){{0, -1}, {1, 1}}, 2) == 0)
{ // this loop ends when semid is removed
data = pop();
dirOpened++;
search_func(data, arg_struct.argv[arg_struct.argc-1],
arg_struct.d, arg_struct.f, arg_struct.l);
free(data);
semop(semid, &(struct sembuf){1, -1}, 1); // "threads at work" -= 1
}
fprintf(stdout, "Thread with id %lu opened %d directories\n",
pthread_self(), dirOpened);
return (void *)dirOpened;
}