#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/syscall.h>
#define MAX_NUM 65536
#ifndef ECHO
#define ECHO(fp, fmt, ...) \
({ \
fprintf(fp, "[File: %s; Line: %u; Func: %s; Date: %s; Time: %s] "fmt"\n", \
__FILE__, __LINE__, __FUNCTION__, __DATE__, __TIME__, ##__VA_ARGS__); \
});
#endif
typedef void *(*pthread_cb_t)(void *);
typedef struct roc_tid_s
{
bool trigger;
pthread_t tid;
}roc_tid_t;
static pid_t gettid(void)
{
return syscall(SYS_gettid);
}
static int service_pthread_stop(pthread_t tid)
{
int ret = 0;
if(tid > 0)
{
#if 1
ret = pthread_kill(tid, 0);
#else
ret = pthread_cancel(tid);
#endif
if(ret == ESRCH)
return 0;
return pthread_join(tid, NULL);
}
return ret;
}
static int service_pthread_start(pthread_t *tid, pthread_attr_t *attr, pthread_cb_t cb, void *arg)
{
int ret = 0;
int scope = PTHREAD_SCOPE_SYSTEM;
int policy = SCHED_RR;
int priority = 50;
size_t stacksize = 8192;
#if 1
int detachstate = PTHREAD_CREATE_JOINABLE;
#else
int detachstate = PTHREAD_CREATE_DETACHED;
#endif
struct sched_param param =
{
.__sched_priority = priority
};
pthread_t default_tid = 0;
pthread_attr_t default_addr;
memset(&default_addr, 0, sizeof(pthread_attr_t));
if(attr)
return pthread_create(tid ? tid : &default_tid, attr, cb, arg);
pthread_attr_init(&default_addr);
pthread_attr_setscope(&default_addr, scope);
pthread_attr_setschedpolicy(&default_addr, policy);
pthread_attr_setschedparam(&default_addr, ¶m);
pthread_attr_setstacksize(&default_addr, stacksize);
pthread_attr_setdetachstate(&default_addr, detachstate);
ret = pthread_create(tid ? tid : &default_tid, &default_addr, cb, arg);
pthread_attr_destroy(&default_addr);
return ret;
}
void* roc_cb (void *arg)
{
int i = 0;
char *p = strdup ("12345678");
pid_t pid = gettid();
pthread_t tid = pthread_self();
roc_tid_t *tids = (roc_tid_t*)arg;
if(tids == NULL)
pthread_exit (NULL);
tids[pid].trigger = true;
tids[pid].tid = tid;
pthread_testcancel();
while (tids[pid].trigger)
{
ECHO(stdout, "roc_cb: %d", i++);
sleep(1);
}
if(p) free(p);
pthread_exit (NULL);
}
int main (int argc, char *argv[])
{
int i = 0;
int ret = 0;
pthread_t tid = 0;
roc_tid_t tids[MAX_NUM];
memset(tids, 0, MAX_NUM*sizeof(roc_tid_t));
for (i = 0; i < 10; i++)
{
ret = service_pthread_start(&tid, NULL, roc_cb, (void*)tids);
if(ret != 0)
{
ECHO(stderr, "%d: %s", errno, strerror(errno));
break;
}
ECHO(stdout, "%d: %lu", i, tid);
}
sleep(3);
for(i = 0; i < MAX_NUM; i++)
{
if(tids[i].trigger) tids[i].trigger = false;
ret = service_pthread_stop(tids[i].tid);
if(ret != 0)
{
ECHO(stderr, "%d: %s", errno, strerror(errno));
break;
}
if(tids[i].tid) ECHO(stdout, "%d: %lu", i, tids[i].tid);
}
return 0;
}
创建/销毁线程操作示例
最新推荐文章于 2023-11-10 18:00:54 发布