+static void release_lock(FILE *f) {
+ if (fclose(f) != 0)
+ die_err("Error releasing lock");
+}
+
+static void *release_lock_after_delay(void *f) {
+ sleep(1);
+ release_lock((FILE *)f);
+ return NULL;
+}
+
+static void *writer_thread(void *start_signal) {
+ ex_t *ex = (ex_t *)malloc(sizeof(ex_t));
+ if (ex == NULL)
+ die_err("Couldn't allocate memory");
+ char *message;
+ if (asprintf(&message, "Hello from thread %lu\n", pthread_self()) == -1)
+ die("Couldn't prepare message");
+ pthread_rwlock_rdlock((pthread_rwlock_t *)start_signal);
+ *ex = write_to_tl_append(message);
+ return ex;
+}
+
+static void write_and_read_line() {
+ remove_logfile();
+ ex_t e = write_to_tl_append("foo\n");
+ verify_log_contents((ex_t[]){e, END});
+}
+
+static void write_and_read_two_lines() {
+ remove_logfile();
+ ex_t e1 = write_to_tl_append("foo\n");
+ ex_t e2 = write_to_tl_append("bar\n");
+ verify_log_contents((ex_t[]){e1, e2, END});
+}
+
+static void write_to_locked_log(char *lock_types[]) {
+ remove_logfile();
+ ex_t e1 = write_to_tl_append("begin\n");
+ FILE *f = fopen(FILENAME, "ae");
+ if (f == NULL)
+ die_err("Couldn't open file for locking");
+ for (int i = 0; lock_types[i]; i++)
+ take_lock(f, lock_types[0]);
+ pthread_t unlock_thread;
+ int create_ret =
+ pthread_create(&unlock_thread, NULL, &release_lock_after_delay, f);
+ if (create_ret != 0) {
+ errno = create_ret;
+ die_err("Couldn't start thread");
+ }
+ ex_t e2 = write_to_tl_append("delayed\n");
+ int join_ret = pthread_join(unlock_thread, NULL);
+ if (join_ret != 0) {
+ errno = join_ret;
+ die_err("Couldn't join thread");
+ }
+ verify_log_contents((ex_t[]){e1, e2, END});
+}
+
+static void write_concurrently() {
+ remove_logfile();
+ const int PARALLELISM = 250;
+ pthread_t threads[PARALLELISM];
+ pthread_rwlock_t start_signal;
+ pthread_rwlock_init(&start_signal, NULL);
+ for (int i = 0; i < PARALLELISM; i++) {
+ int create_ret =
+ pthread_create(&threads[i], NULL, &writer_thread, &start_signal);
+ if (create_ret != 0) {
+ errno = create_ret;
+ die_err("Couldn't start thread");
+ }
+ }
+ pthread_rwlock_unlock(&start_signal);
+ ex_t results[PARALLELISM + 1];
+ for (int i = 0; i < PARALLELISM; i++) {
+ ex_t *ex;
+ int join_ret = pthread_join(threads[i], (void **)&ex);
+ if (join_ret != 0) {
+ errno = join_ret;
+ die_err("Couldn't join thread");
+ }
+ results[i] = *ex;
+ free(ex);
+ }
+ results[PARALLELISM] = END;
+ verify_log_contents_unordered(results);
+ for (int i = 0; i < PARALLELISM; i++) {
+ free((void *)results[i].message);
+ }
+}
+
+int main() {
+ test_encode_time();
+ write_and_read_line();
+ write_and_read_two_lines();
+ write_to_locked_log((char *[]){NULL});
+ write_to_locked_log((char *[]){"fcntl", NULL});
+ write_to_locked_log((char *[]){"flock", NULL});
+ write_to_locked_log((char *[]){"flock", "fcntl", NULL}); /* Deadlock risk! */
+ write_to_locked_log((char *[]){"fcntl", "flock", NULL});
+ write_concurrently();
+}