Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>dispatch_read</code> and <code>dispatch_write</code> are not synchronous calls -- that's their whole point. In other words, the way you have it set up here, you <code>close</code> the file descriptor right after calling <code>dispatch_write</code>. By the time GCD goes to perform the write on a background thread, the file descriptor is already closed. Same for the read operation. You have to wait until the write operation is finished before you close the file.</p> <p>I reworked your code a little bit to use a <code>dispatch_semaphore</code> to wait for the writes and reads to complete before closing the file:</p> <pre><code>int main() { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); int intbuffer[] = { 1, 2, 3, 4 }; dispatch_data_t data = dispatch_data_create(intbuffer, 4 * sizeof(int), queue, NULL); dispatch_semaphore_t sem = dispatch_semaphore_create(0); // Write dispatch_fd_t fd = open("/tmp/data.dat", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXG | S_IRWXO); printf("FD: %d\n", fd); dispatch_write(fd, data, queue,^(dispatch_data_t d, int e) { printf("Written %zu bytes!\n", dispatch_data_get_size(data) - (d ? dispatch_data_get_size(d) : 0)); printf("\tError: %d\n", e); dispatch_semaphore_signal(sem); }); dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); close(fd); // Read fd = open("/tmp/data.dat", O_RDWR); dispatch_read(fd, 4 * sizeof(int), queue, ^(dispatch_data_t d, int e) { printf("Read %zu bytes!\n", dispatch_data_get_size(d)); printf("\tError: %d\n", e); dispatch_semaphore_signal(sem); }); dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); close(fd); // Exit confirmation getchar(); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload