
作業(yè)社區(qū)
探索學習新天地,共享知識資源!
蠟筆小方哎 的學生作業(yè):
#include #include #include #include struct person { char name[20]; int age; }; void* thread_func(void* arg) { struct person* ret = (struct person*)malloc(sizeof(struct person)); strcpy(ret->name, "aaa"); ret->age = 15; pthread_exit((void*)ret); } int main() { int err; pthread_t pid; err = pthread_create(&pid, NULL, thread_func, NULL); if(err != 0) { fprintf(stderr, "pthread_create() error: %s\n", strerror(err)); exit(-1); } struct person* p; pthread_join(pid, (void**)&p); printf("name: %s, age: %d\n", p->name, p->age); free(p); return 0; }
蠟筆小方哎 的學生作業(yè):
fang@fang:~/Projects/test$ cat main.c #include #include #include #include #include void* do_thread(void* arg) { printf("current threadid: %d\n", pthread_self()); } int main() { pthread_t tid_1, tid_2; int err; err = pthread_create(&tid_1, NULL, do_thread, NULL); if(err != 0) { fprintf(stderr, "error: %s\n", strerror(err)); exit(-1); } err = pthread_create(&tid_2, NULL, do_thread, NULL); if(err != 0) { fprintf(stderr, "error: %s\n", strerror(err)); exit(-1); } pthread_detach(tid_1); pthread_detach(tid_2); sleep(1); return 0; }
蠟筆小方哎 的學生作業(yè):
#include #include #include #include #include #include #include #include #include #include #define SEM_SET_PATH "." #define SEM_SET_PROJ_ID 'C' union semun{ unsigned short* array; }; // 得到當前時間字符串,精確到毫秒 // 參數一是字符串變量,參數二是它的長度 void get_time_str_ms(char *time_str, int len) { struct timeval tv; struct timezone tz; struct tm *p; memset(time_str, 0, len); gettimeofday(&tv,&tz); p = localtime(&tv.tv_sec); sprintf(time_str,"%d-%02d-%02d %02d:%02d:%02d", (1900+p->tm_year),(1+p->tm_mon),p->tm_mday,(p->tm_hour),p->tm_min,p->tm_sec); } int main() { key_t key; pid_t pid; int semid; union semun s; unsigned short values[2] = {1, 0}; s.array = values; char* filename = "test.txt"; key = ftok(SEM_SET_PATH, SEM_SET_PROJ_ID); if(key == -1) { perror("ftok() error!\n"); exit(-1); } printf("key = %d\n", key); semid = semget(key, 2, IPC_CREAT|0644); if(semid == -1) { perror("semget() error!\n"); exit(-1); } printf("semid = %d\n", semid); if(semctl(semid, 0, SETALL, s) == -1) { perror("semctl() SETALL error!\n"); exit(-1); } pid = fork(); if(pid == -1) { perror("fork() error!\n"); exit(-1); } else if(pid == 0) { char time[50]; FILE* fp; struct sembuf sops; sops.sem_flg = SEM_UNDO; for(int i=0; i